private bool ShouldSetToken(HttpRequestMessage request)
        {
            // There is no current http context, proactive message
            // assuming that developer is not calling drop context
            if (HttpContext.Current == null || TrustedUri(request.RequestUri))
            {
                return(true);
            }
            else if (HttpContext.Current.User != null)
            {
                // This check is redundant now because RequestUri should already be in the
                // trusted uri list added by BotAuthentication attribute
                ClaimsIdentity identity = (ClaimsIdentity)HttpContext.Current.User.Identity;

                if (identity?.Claims.FirstOrDefault(c => c.Type == "appid" && JwtConfig.GetToBotFromChannelTokenValidationParameters(MicrosoftAppId).ValidIssuers.Contains(c.Issuer)) != null)
                {
                    return(true);
                }

                // Fallback for BF-issued tokens
                if (identity?.Claims.FirstOrDefault(c => c.Issuer == "https://api.botframework.com" && c.Type == "aud") != null)
                {
                    return(true);
                }

                // For emulator, we fallback to MSA as valid issuer
                if (identity?.Claims.FirstOrDefault(c => c.Type == "appid" && JwtConfig.ToBotFromMSATokenValidationParameters.ValidIssuers.Contains(c.Issuer)) != null)
                {
                    return(true);
                }
            }

            Trace.TraceWarning($"Service url {request.RequestUri.Authority} is not trusted and JwtToken cannot be sent to it.");
            return(false);
        }
        private bool ShouldSetToken()
        {
            // There is no current http context, proactive message
            // assuming that developer is not calling drop context
            if (HttpContext.Current == null)
            {
                return(true);
            }
            else if (HttpContext.Current.User != null)
            {
                ClaimsIdentity identity = (ClaimsIdentity)HttpContext.Current.User.Identity;

                if (identity?.Claims.FirstOrDefault(c => c.Type == "appid" && JwtConfig.GetToBotFromChannelTokenValidationParameters(MicrosoftAppId).ValidIssuers.Contains(c.Issuer)) != null)
                {
                    return(true);
                }

                // Fallback for BF-issued tokens
                if (identity?.Claims.FirstOrDefault(c => c.Issuer == "https://api.botframework.com" && c.Type == "aud") != null)
                {
                    return(true);
                }

                // For emulator, we fallback to MSA as valid issuer
                if (identity?.Claims.FirstOrDefault(c => c.Type == "appid" && JwtConfig.ToBotFromMSATokenValidationParameters.ValidIssuers.Contains(c.Issuer)) != null)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #3
0
        public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            MicrosoftAppId = MicrosoftAppId ?? ConfigurationManager.AppSettings[MicrosoftAppIdSettingName ?? "MicrosoftAppId"];

            if (Debugger.IsAttached && String.IsNullOrEmpty(MicrosoftAppId))
            {
                // then auth is disabled
                return;
            }

            var tokenExtractor = new JwtTokenExtractor(JwtConfig.GetToBotFromChannelTokenValidationParameters(MicrosoftAppId), OpenIdConfigurationUrl);
            var identity       = await tokenExtractor.GetIdentityAsync(actionContext.Request);

            // No identity? If we're allowed to, fall back to MSA
            // This code path is used by the emulator
            if (identity == null && !DisableSelfIssuedTokens)
            {
                tokenExtractor = new JwtTokenExtractor(JwtConfig.ToBotFromMSATokenValidationParameters, JwtConfig.ToBotFromMSAOpenIdMetadataUrl);
                identity       = await tokenExtractor.GetIdentityAsync(actionContext.Request);

                // Check to make sure the app ID in the token is ours
                if (identity != null)
                {
                    // If it doesn't match, throw away the identity
                    if (tokenExtractor.GetBotIdFromClaimsIdentity(identity) != MicrosoftAppId)
                    {
                        identity = null;
                    }
                }
            }

            // Still no identity? Fail out.
            if (identity == null)
            {
                tokenExtractor.GenerateUnauthorizedResponse(actionContext);
                return;
            }

            Thread.CurrentPrincipal = new ClaimsPrincipal(identity);

            // Inside of ASP.NET this is required
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = Thread.CurrentPrincipal;
            }

            await base.OnAuthorizationAsync(actionContext, cancellationToken);
        }
        private JwtTokenExtractor GetTokenExtractor()
        {
            var parameters = JwtConfig.GetToBotFromChannelTokenValidationParameters((audiences, securityToken, validationParameters) => true);

            return(new JwtTokenExtractor(parameters, this.openIdConfigurationUrl));
        }
Example #5
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)
        {
            MicrosoftAppId = MicrosoftAppId ?? _configuration[MicrosoftAppIdSettingName];

            if (Debugger.IsAttached && String.IsNullOrEmpty(MicrosoftAppId))
            {
                // then auth is disabled
                return;
            }

            var tokenExtractor = new JwtTokenExtractor(JwtConfig.GetToBotFromChannelTokenValidationParameters(MicrosoftAppId), OpenIdConfigurationUrl);

            var frameRequestHeaders = actionContext.HttpContext.Request.Headers as FrameRequestHeaders;

            if (frameRequestHeaders == null)
            {
                //TODO: ...
                throw new NotSupportedException("frameRequestHeaders is null");
            }

            //TODO: Надо проверить!
            var identity = await tokenExtractor.GetIdentityAsync(frameRequestHeaders.HeaderAuthorization.FirstOrDefault());

            // No identity? If we're allowed to, fall back to MSA
            // This code path is used by the emulator
            if (identity == null && !DisableSelfIssuedTokens)
            {
                tokenExtractor = new JwtTokenExtractor(JwtConfig.ToBotFromMSATokenValidationParameters, JwtConfig.ToBotFromMSAOpenIdMetadataUrl);

                //TODO: Надо проверить!
                identity = await tokenExtractor.GetIdentityAsync(frameRequestHeaders.HeaderAuthorization.FirstOrDefault());

                // Check to make sure the app ID in the token is ours
                if (identity != null)
                {
                    // If it doesn't match, throw away the identity
                    if (tokenExtractor.GetBotIdFromClaimsIdentity(identity) != MicrosoftAppId)
                    {
                        identity = null;
                    }
                }
            }

            // Still no identity? Fail out.
            if (identity == null)
            {
                tokenExtractor.GenerateUnauthorizedResponse(actionContext);
                return;
            }

            var activity = actionContext.ActionArguments.Select(t => t.Value).OfType <Activity>().FirstOrDefault();

            if (activity != null)
            {
                MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);
            }
            else
            {
                // No model binding to activity check if we can find JObject or JArray
                var obj = actionContext.ActionArguments.Where(t => t.Value is JObject || t.Value is JArray).Select(t => t.Value).FirstOrDefault();
                if (obj != null)
                {
                    Activity[] activities = (obj is JObject) ? new Activity[] { ((JObject)obj).ToObject <Activity>() } : ((JArray)obj).ToObject <Activity[]>();
                    foreach (var jActivity in activities)
                    {
                        if (!string.IsNullOrEmpty(jActivity.ServiceUrl))
                        {
                            MicrosoftAppCredentials.TrustServiceUrl(jActivity.ServiceUrl);
                        }
                    }
                }
                else
                {
                    //LOG: Trace.TraceWarning("No activity in the Bot Authentication Action Arguments");
                }
            }

            //Thread.CurrentPrincipal = new ClaimsPrincipal(identity);

            // Inside of ASP.NET this is required
            if (_httpContextAccessor.HttpContext != null)
            {
                _httpContextAccessor.HttpContext.User = new ClaimsPrincipal(identity);
            }

            await base.OnActionExecutionAsync(actionContext, next);
        }