private static AudienceRestriction GetAudienceRestriction(Saml2AuthenticationOptions options)
        {
            if (!options.TokenValidationParameters.ValidateAudience)
            {
                return(new AudienceRestriction(AudienceUriMode.Never));
            }

            var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);

            if (!string.IsNullOrWhiteSpace(options.Wtrealm))
            {
                audienceRestriction.AllowedAudienceUris.Add(new Uri(options.Wtrealm));
            }

            if (!string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
            {
                audienceRestriction.AllowedAudienceUris.Add(new Uri(options.TokenValidationParameters.ValidAudience));
            }

            if (options.TokenValidationParameters.ValidAudiences != null)
            {
                foreach (var audience in options.TokenValidationParameters.ValidAudiences)
                {
                    audienceRestriction.AllowedAudienceUris.Add(new Uri(audience));
                }
            }

            return(audienceRestriction);
        }
        /// <summary>
        /// Adds the <see cref="Saml2AuthenticationMiddleware"/> into the OWIN runtime.
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="options">SamlAuthenticationOptions configuration options</param>
        /// <returns>The updated <see cref="IAppBuilder"/></returns>
        public static IAppBuilder UseSaml2Authentication(this IAppBuilder app, Saml2AuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            app.Use(typeof(Saml2AuthenticationMiddleware), app, options);
            return(app);
        }
        private static HttpMessageHandler ResolveHttpMessageHandler(Saml2AuthenticationOptions options)
        {
            var handler = options.BackchannelHttpHandler ?? new WebRequestHandler();

            if (options.BackchannelCertificateValidator != null)
            {
                var webRequestHandler = handler as WebRequestHandler;

                if (webRequestHandler == null)
                {
                    throw new InvalidOperationException("An ICertificateValidator cannot be specified at the same time as an HttpMessageHandler unless it is a WebRequestHandler.");
                }

                webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
            }

            return(handler);
        }
        private static string GetRedirectUri(Saml2Binding binding, Saml2AuthenticationOptions options)
        {
            var relayState = binding.GetRelayStateQuery();

            if (relayState.ContainsKey(_relayStateRedirectUri))
            {
                var redirectUri = relayState[_relayStateRedirectUri];
                return(redirectUri);
            }

            if (relayState.ContainsKey(_relayStateReturnUrl))
            {
                var returnUrl   = relayState[_relayStateReturnUrl];
                var redirectUri = options.ExternalLoginCallbackPath.Add(new QueryString(_relayStateReturnUrl, returnUrl));
                return(redirectUri);
            }

            return(options.ExternalLoginCallbackPath.Value);
        }
        private static Saml2AuthnResponse GetSaml2AuthnResponse(Saml2AuthenticationOptions options)
        {
            var handler = new Saml2ResponseSecurityTokenHandler
            {
                Configuration = new SecurityTokenHandlerConfiguration
                {
                    SaveBootstrapContext      = false,
                    AudienceRestriction       = GetAudienceRestriction(options),
                    IssuerNameRegistry        = new Saml2ResponseIssuerNameRegistry(),
                    CertificateValidationMode = X509CertificateValidationMode.None,
                    RevocationMode            = X509RevocationMode.NoCheck,
                    CertificateValidator      = options.TokenValidationParameters.CertificateValidator ?? X509CertificateValidator.None,
                    DetectReplayedTokens      = false,
                },
                SamlSecurityTokenRequirement = { NameClaimType = ClaimTypes.NameIdentifier }
            };

            return(new InternalSaml2AuthnResponse(handler));
        }
        public Saml2AuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, Saml2AuthenticationOptions options)
            : base(next, app, options)
        {
            _logger = app.CreateLogger <Saml2AuthenticationMiddleware>();

            Options.SecurityTokenHandlers.AddOrReplace(new Saml2ResponseSecurityTokenHandler());

            var configurationManager = options.ConfigurationManager as ConfigurationManager <WsFederationConfiguration>;

            if (configurationManager != null)
            {
                var httpClient = new HttpClient(ResolveHttpMessageHandler(options))
                {
                    Timeout = Options.BackchannelTimeout,
                    MaxResponseContentBufferSize = 1024 * 1024 * 10
                };

                options.ConfigurationManager = new Saml2ConfigurationManager(options.MetadataAddress, httpClient);

                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("MetadataAddress={0}", options.MetadataAddress));
            }
        }