コード例 #1
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (await Options.CredentialProvider.IsAuthenticationDisabledAsync())
            {
                var principal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Role, "Bot") }));
                return(AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme)));
            }

            string token = null;

            string authorization = Request.Headers["Authorization"];

            token = authorization?.Substring("Bearer ".Length).Trim();

            // If no token found, no further work possible
            // and Authentication is not disabled fail
            if (string.IsNullOrEmpty(token))
            {
                return(AuthenticateResult.Fail("No JwtToken is present and BotAuthentication is enabled!"));
            }

            var authenticator = new BotAuthenticator(Options.CredentialProvider, Options.OpenIdConfiguration, Options.DisableEmulatorTokens);
            var identityToken = await authenticator.TryAuthenticateAsync(Options.AuthenticationScheme, token, CancellationToken.None);

            if (identityToken.Authenticated)
            {
                identityToken.Identity.AddClaim(new Claim(ClaimTypes.Role, "Bot"));
                var principal = new ClaimsPrincipal(identityToken.Identity);
                var ticket    = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);
                Context.User = principal;

                if (Options.SaveToken)
                {
                    ticket.Properties.StoreTokens(new[]
                    {
                        new AuthenticationToken {
                            Name = "access_token", Value = token
                        }
                    });
                }

                return(AuthenticateResult.Success(ticket));
            }
            else
            {
                return(AuthenticateResult.Fail($"Failed to authenticate JwtToken {token}"));
            }
        }
コード例 #2
0
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            var provider         = this.GetCredentialProvider();
            var botAuthenticator = new BotAuthenticator(provider, OpenIdConfigurationUrl, DisableEmulatorTokens);
            var identityToken    = await botAuthenticator.TryAuthenticateAsync(actionContext.Request, cancellationToken);

            // the request is not authenticated, fail with 401.
            if (!identityToken.Authenticated)
            {
                actionContext.Response = BotAuthenticator.GenerateUnauthorizedResponse(actionContext.Request);
                return;
            }

            botAuthenticator.TrustServiceUrls(identityToken, GetActivities(actionContext));
            await base.OnActionExecutingAsync(actionContext, cancellationToken);
        }
コード例 #3
0
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            var provider         = this.GetCredentialProvider();
            var botAuthenticator = new BotAuthenticator(provider, OpenIdConfigurationUrl, DisableEmulatorTokens);
            var identityToken    = await botAuthenticator.TryAuthenticateAsync(actionContext.Request, cancellationToken);

            // the request is not authenticated, fail with 401.
            if (!identityToken.Authenticated)
            {
                actionContext.Response = GenerateUnauthorizedResponse(actionContext.Request);
                return;
            }

            // authenticated but no identity, auth is disabled;
            if (identityToken.Authenticated && identityToken.Identity == null)
            {
                await base.OnActionExecutingAsync(actionContext, cancellationToken);

                return;
            }

            // trust the service url in activities
            var activities = GetActivities(actionContext);

            if (activities.Any())
            {
                foreach (var activity in activities)
                {
                    MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);
                }
            }
            else
            {
                Trace.TraceWarning("No ServiceUrls added to trusted list");
            }

            await base.OnActionExecutingAsync(actionContext, cancellationToken);
        }
コード例 #4
0
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            var provider         = this.GetCredentialProvider();
            var botAuthenticator = new BotAuthenticator(provider, OpenIdConfigurationUrl, DisableEmulatorTokens);

            try
            {
                var authenticated = await botAuthenticator.TryAuthenticateAsync(actionContext.Request, GetActivities(actionContext), cancellationToken);

                // the request is not authenticated, fail with 401.
                if (!authenticated)
                {
                    actionContext.Response = BotAuthenticator.GenerateUnauthorizedResponse(actionContext.Request, "BotAuthenticator failed to authenticate incoming request!");
                    return;
                }
            }
            catch (Exception e)
            {
                actionContext.Response = BotAuthenticator.GenerateUnauthorizedResponse(actionContext.Request, $"Failed authenticating incoming request: {e.ToString()}");
                return;
            }

            await base.OnActionExecutingAsync(actionContext, cancellationToken);
        }
コード例 #5
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var provider         = this.GetCredentialProvider();
            var botAuthenticator = new BotAuthenticator(provider, GetOpenIdConfigurationUrl(), DisableEmulatorTokens);

            try
            {
                var identityToken = await botAuthenticator.AuthenticateAsync(context.HttpContext.Request,
                                                                             GetActivities(context), context.HttpContext.RequestAborted);

                // the request is not authenticated, fail with 401.
                if (!identityToken.Authenticated)
                {
                    context.Result = BotAuthenticator.GenerateUnauthorizedResponse(context.HttpContext, "BotAuthenticator failed to authenticate incoming request!");
                    return;
                }
            }
            catch (Exception e)
            {
                context.Result = BotAuthenticator.GenerateUnauthorizedResponse(context.HttpContext, $"Failed authenticating incoming request: {e.ToString()}");
                return;
            }
            await next();
        }
コード例 #6
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (await Options.CredentialProvider.IsAuthenticationDisabledAsync())
            {
                var principal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Role, "Bot") }));

                var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
                {
                    Principal = principal
                };
                tokenValidatedContext.Success();
                return(tokenValidatedContext.Result);
            }

            string token = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options);

                // event can set the token
                await Events.MessageReceived(messageReceivedContext);

                if (messageReceivedContext.Result != null)
                {
                    return(messageReceivedContext.Result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.NoResult());
                    }

                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("Bearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.NoResult());
                    }
                }

                // If no token found, no further work possible
                // and Authentication is not disabled fail
                if (string.IsNullOrEmpty(token))
                {
                    return(AuthenticateResult.Fail("No JwtToken is present and BotAuthentication is enabled!"));
                }
                var authenticator = new BotAuthenticator(Options.CredentialProvider, Options.OpenIdConfiguration, Options.DisableEmulatorTokens);
                var identityToken = await authenticator.TryAuthenticateAsync(Options.Challenge, token, CancellationToken.None);

                if (identityToken.Authenticated)
                {
                    Logger.TokenValidationSucceeded();

                    identityToken.Identity.AddClaim(new Claim(ClaimTypes.Role, "Bot"));
                    var principal = new ClaimsPrincipal(identityToken.Identity);
                    Context.User = principal;

                    var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
                    {
                        Principal     = principal,
                        SecurityToken = new JwtSecurityToken(token)
                    };

                    await Events.TokenValidated(tokenValidatedContext);

                    if (tokenValidatedContext.Result != null)
                    {
                        return(tokenValidatedContext.Result);
                    }

                    if (Options.SaveToken)
                    {
                        tokenValidatedContext.Properties.StoreTokens(new[]
                        {
                            new AuthenticationToken {
                                Name = "access_token", Value = token
                            }
                        });
                    }

                    tokenValidatedContext.Success();
                    return(tokenValidatedContext.Result);
                }
                else
                {
                    Logger.TokenValidationFailed(token, null);
                    return(AuthenticateResult.Fail($"Failed to authenticate JwtToken {token}"));
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorProcessingMessage(ex);

                var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
                {
                    Exception = ex
                };

                await Events.AuthenticationFailed(authenticationFailedContext);

                if (authenticationFailedContext.Result != null)
                {
                    return(authenticationFailedContext.Result);
                }

                throw;
            }
        }