Пример #1
0
        /// <summary>
        /// Loads the settings for the IdentityConfiguration from the application or web configuration file.
        /// </summary>
        /// <remarks>
        /// If there is no configuration file, or the named section does not exist, then no exception is thrown,
        /// instead the class is loaded with a set of default values.
        /// </remarks>
        protected void LoadConfiguration(IdentityConfigurationElement element)
        {
            if (element != null)
            {
                //
                // Load the claims authentication manager
                //
                if (element.ClaimsAuthenticationManager.IsConfigured)
                {
                    _claimsAuthenticationManager = GetClaimsAuthenticationManager(element);
                }

                //
                // Load the claims authorization manager.
                //
                if (element.ClaimsAuthorizationManager.IsConfigured)
                {
                    _claimsAuthorizationManager = CustomTypeElement.Resolve <ClaimsAuthorizationManager>(element.ClaimsAuthorizationManager);
                }

                //
                // Load the service level Security Token Handler configuration
                //
                _serviceHandlerConfiguration = LoadHandlerConfiguration(element);
            }

            //
            // Reads handler configuration via LoadConfiguredHandlers. Do this last.
            //
            _securityTokenHandlerCollectionManager = LoadHandlers(element);
        }
        public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.RawResponse == null ||
                configuration == null)
            {
                throw new ArgumentNullException();
            }

            // search for signatures (possibly multiple)
            var signatureNodes = token.RawResponse.GetElementsByTagName("Signature", Namespaces.XMLDSIG);

            foreach (XmlElement signatureNode in signatureNodes)
            {
                var signedXml = new SignedXml(signatureNode.ParentNode as XmlElement);
                signedXml.LoadXml(signatureNode);
                signedXml.SafeCanonicalizationMethods.Add("http://www.w3.org/TR/1999/REC-xpath-19991116");

                var result = signedXml.CheckSignature();

                if (!result)
                {
                    throw new ValidationException("Token's signature validation failed");
                }
            }
        }
        private static AuthenticationHandler GetDefaultAuthenticationHandler()
        {
            var authConfig = new AuthenticationConfiguration
            {
                RequireSsl = false,
                InheritHostClientIdentity = false
            };

            #region Basic Authentication
            authConfig.AddBasicAuthentication((userName, password) => { return(userName == password); });
            #endregion

            //#region SWT
            //authConfig.Handler.AddSimpleWebToken(
            //    "SWT",
            //    Constants.Issuer,
            //    Constants.Realm,
            //    "Dc9Mpi3jbooUpBQpB/4R7XtUsa3D/ALSjTVvK8IUZbg=");
            //#endregion

            #region SAML2 tokens
            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("D263DDCF598E716F0037380796A4A62DF017ADB8", "TEST");

            var saml2Config = new SecurityTokenHandlerConfiguration();
            saml2Config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://test"));
            saml2Config.IssuerNameRegistry   = registry;
            saml2Config.CertificateValidator = X509CertificateValidator.None;

            authConfig.AddSaml2(saml2Config, AuthenticationOptions.ForAuthorizationHeader("Saml2"), null);
            #endregion

            var authHandler = new AuthenticationHandler(authConfig);
            return(authHandler);
        }
Пример #4
0
        public Saml2Serializer()
        {
            Configuration = new SecurityTokenHandlerConfiguration()
            {

            };
        }
        public void AddJsonWebToken(string issuer, string audience, string signingKey, AuthenticationOptions options)
        {
            var config   = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();

            registry.AddTrustedIssuer(issuer, issuer);
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();

            issuerResolver.AddSigningKey(issuer, signingKey);
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience));

            var handler = new JsonWebTokenHandler();

            handler.Configuration = config;

            AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection {
                    handler
                },
                Options = options
            });
        }
Пример #6
0
        /// <summary>
        /// Validate the assertion
        /// </summary>
        /// <param name="assertion"></param>
        /// <returns></returns>
        protected ClaimsIdentity ValidateSamlToken(SecurityToken assertion)
        {
            Saml2PropertiesRemoval(assertion);

            var configuration = new SecurityTokenHandlerConfiguration();

            configuration.RevocationMode = X509RevocationMode.NoCheck;

            // You can flip this switch if you don't want to make sure that IDP certificate
            // is in the trusted root store of the Local Machine
            // configuration.CertificateValidator = X509CertificateValidator.None;
            configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            configuration.CertificateValidationMode        = X509CertificateValidationMode.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();

            registry.AddTrustedIssuer(_config.CertificateThumbprint, _config.Name);
            configuration.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

            try
            {
                var identity = handler.ValidateToken(assertion).First();

                return(identity);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static TokenValidationParameters LoadFromConfig(
            SecurityTokenHandlerConfiguration securityTokenHandlerConfiguration)
        {
            var wsFederationAuthenticationIssuer = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Issuer;

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer       = !string.IsNullOrEmpty(wsFederationAuthenticationIssuer),
                ValidIssuer          = wsFederationAuthenticationIssuer,
                SaveSigninToken      = securityTokenHandlerConfiguration.SaveBootstrapContext,
                ClockSkew            = securityTokenHandlerConfiguration.MaxClockSkew,
                CertificateValidator = securityTokenHandlerConfiguration.CertificateValidator
            };

            if (securityTokenHandlerConfiguration.AudienceRestriction.AudienceMode == AudienceUriMode.Always && securityTokenHandlerConfiguration.AudienceRestriction.AllowedAudienceUris.Any())
            {
                tokenValidationParameters.ValidateAudience = true;
                tokenValidationParameters.ValidAudiences   =
                    securityTokenHandlerConfiguration.AudienceRestriction.AllowedAudienceUris.Select(x => x.AbsoluteUri);
            }
            else
            {
                tokenValidationParameters.ValidateAudience = false;
            }

            return(tokenValidationParameters);
        }
        public static SecurityToken DeSerializeSecurityToken(string tokenString, string issuerThumbPrint, string issuerThumbprintName)
        {
            XmlTextReader xmlTextReader            = new XmlTextReader(new StringReader(tokenString));
            SecurityTokenHandlerConfiguration conf = new SecurityTokenHandlerConfiguration()
            {
                SaveBootstrapContext = true
            };

            conf.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            ConfigurationBasedIssuerNameRegistry actAsRegistry = new ConfigurationBasedIssuerNameRegistry();

            actAsRegistry.AddTrustedIssuer(issuerThumbPrint, issuerThumbPrint);
            conf.IssuerNameRegistry = actAsRegistry;
            List <SecurityToken> tokens = new List <SecurityToken>()
            {
                new X509SecurityToken(Constants.DefaultCertificate)
            };

            conf.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(tokens), true);
            SecurityTokenHandlerCollection handlers = new SecurityTokenHandlerCollection(conf)
            {
                new X509CertificateSessionSecurityTokenHandler(Constants.DefaultCertificate),
                new UserNameTokenHandler(),
                new SamlTokenHandler(),
                new EncryptedSecurityTokenHandler()
            };

            return(handlers.ReadToken(xmlTextReader));
        }
        private HttpResponseMessage CreateTokenResponse(GenericXmlSecurityToken token, string scope)
        {
            var response = new TokenResponse();

            if (ConfigurationRepository.AdfsIntegration.PassThruAuthenticationToken)
            {
                response.AccessToken = token.TokenXml.OuterXml;
                response.ExpiresIn   = (int)(token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds);
            }
            else
            {
                var bridge = new AdfsBridge(ConfigurationRepository);
                if (ConfigurationRepository.Keys.DecryptionCertificate != null)
                {
                    var configuration = new SecurityTokenHandlerConfiguration
                    {
                        AudienceRestriction       = { AudienceMode = AudienceUriMode.Never },
                        CertificateValidationMode = X509CertificateValidationMode.None,
                        RevocationMode            = X509RevocationMode.NoCheck,
                        CertificateValidator      = X509CertificateValidator.None,
                        ServiceTokenResolver      = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                            new ReadOnlyCollection <SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false)
                    };
                    var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(handler), scope);
                }
                else
                {
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(), scope);
                }
            }

            return(Request.CreateResponse <TokenResponse>(HttpStatusCode.OK, response));
        }
        /// <summary>Converts a SecurityToken to an IClaimsPrincipal.</summary>
        /// <param name="token">The token.</param>
        /// <param name="signingCertificate">The signing certificate.</param>
        /// <returns>An IClaimsPrincipal</returns>
        public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, X509Certificate2 signingCertificate)
        {
            SecurityTokenHandlerConfiguration standardConfiguration = CreateStandardConfiguration(signingCertificate);

            return(ToClaimsPrincipal(token,
                                     CreateDefaultHandlerCollection(standardConfiguration)));
        }
Пример #11
0
        public static IEnumerable <Claim> ValidateIdentityToken(string token, string issuer, string audience, X509Certificate2 signingCertificate, X509CertificateValidator certificateValidator = null)
        {
            if (certificateValidator == null)
            {
                certificateValidator = X509CertificateValidator.None;
            }

            var configuration = new SecurityTokenHandlerConfiguration
            {
                CertificateValidator = certificateValidator
            };

            var handler = new JwtSecurityTokenHandler
            {
                Configuration = configuration
            };

            var parameters = new TokenValidationParameters
            {
                ValidIssuer        = issuer,
                ValidAudience      = audience,
                IssuerSigningToken = new X509SecurityToken(signingCertificate)
            };

            SecurityToken wat = null;

            return(handler.ValidateToken(token, parameters, out wat).Claims);
        }
Пример #12
0
        public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.Response == null || configuration == null)
            {
                throw new ArgumentNullException();
            }

            if (token.Response.Assertions != null)
            {
                foreach (var assertion in token.Response.Assertions)
                {
                    if (assertion.Conditions != null)
                    {
                        ValidateNotBefore(assertion.Conditions.NotBefore, configuration.MaxClockSkew);
                        ValidateNotOnOrAfter(assertion.Conditions.NotOnOrAfter, configuration.MaxClockSkew);
                    }
                    if (
                        assertion.Subject != null &&
                        assertion.Subject.SubjectConfirmation != null &&
                        assertion.Subject.SubjectConfirmation.SubjectConfirmationData != null
                        )
                    {
                        ValidateNotBefore(assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotBefore, configuration.MaxClockSkew);
                        ValidateNotOnOrAfter(assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter, configuration.MaxClockSkew);
                    }
                }
            }
        }
Пример #13
0
        private static void ValidateSwtToken(string tokenString)
        {
            var configuration = new SecurityTokenHandlerConfiguration();
            var validationKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signingKey));

            // audience validation
            configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(realm));

            // signature & issuer validation
            var resolverTable = new Dictionary <string, IList <SecurityKey> >
            {
                { issuerUri, new SecurityKey[] { validationKey } }
            };

            configuration.IssuerTokenResolver = new NamedKeyIssuerTokenResolver(resolverTable);

            var handler = new SimpleWebTokenHandler();

            handler.Configuration = configuration;

            var token = handler.ReadToken(tokenString);
            var ids   = handler.ValidateToken(token);

            "\n\nValidated Claims:".ConsoleYellow();
            foreach (var claim in ids.First().Claims)
            {
                Console.WriteLine("{0}\n {1}\n", claim.Type, claim.Value);
            }
        }
Пример #14
0
        private ClaimsPrincipal ParseToken(GenericXmlSecurityToken genericToken)
        {
            using (XmlReader samlReader = XmlReader.Create(new StringReader(genericToken.TokenXml.OuterXml)))
            {
                SecurityTokenHandlerCollection tokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();

                SecurityTokenHandlerConfiguration config = tokenHandlers.Configuration;
                var securityTokens = new List <SecurityToken>
                {
                    new X509SecurityToken(CertificateHelper.GetCertificate(_tokenClientOptions.StoreName, _tokenClientOptions.StoreLocation, _tokenClientOptions.SubjectDistinguishedName))
                };

                config.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(securityTokens.AsReadOnly(), false);
                config.CertificateValidator = X509CertificateValidator.PeerOrChainTrust;

                config.IssuerTokenResolver = new X509CertificateStoreTokenResolver(_tokenClientOptions.StoreName, _tokenClientOptions.StoreLocation);
                config.IssuerNameRegistry  = _nameRegistry;

                config.AudienceRestriction.AllowedAudienceUris.Add(_tokenClientOptions.AudienceUri);
                SecurityToken samlToken = tokenHandlers.ReadToken(samlReader);

                ClaimsIdentity tokenIdentity = tokenHandlers.ValidateToken(samlToken).FirstOrDefault();
                return(new ClaimsPrincipal(tokenIdentity));
            }
        }
        public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.Response == null ||
                configuration == null)
            {
                throw new ArgumentNullException();
            }
            if (configuration.IssuerNameRegistry == null)
            {
                throw new ArgumentNullException("configuration", "Issuer name registry cannot empty in the configuration");
            }

            if (token.Response.Assertions != null)
            {
                foreach (var assertion in token.Response.Assertions)
                {
                    var securityToken = assertion.GetX509SecurityToken();
                    if (securityToken != null)
                    {
                        var issuer = configuration.IssuerNameRegistry.GetIssuerName(securityToken);
                        if (string.IsNullOrEmpty(issuer))
                        {
                            throw new ValidationException("Issuer name registry doesn't recognize token's certificate");
                        }
                    }
                }
            }
        }
        private ClaimsPrincipal GetClaimsPrincipal(SignInResponseMessage signInResponse)
        {
            try
            {
                //configure the certificate and some service token handler configuration properties (these basically match the web.config settings for MVC 4/5 app).
                SecurityTokenHandlerConfiguration config = new SecurityTokenHandlerConfiguration();
                config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Options.Realm));
                config.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; //we have dodgy certs in dev

                ConfigurationBasedIssuerNameRegistry inr = new ConfigurationBasedIssuerNameRegistry();
                inr.AddTrustedIssuer(Options.SigningCertThumbprint, Options.ClaimsIssuer);
                config.IssuerNameRegistry   = inr;
                config.CertificateValidator = System.IdentityModel.Selectors.X509CertificateValidator.None; //we have dodgy certs in dev

                //Load up an XmlDocument with the result. Have to use XmlDocument so we can generate a valid reader unfortunately.
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(signInResponse.Result);

                //Add the namespaces and search for Assertion or EncryptedAssertion
                XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDoc.NameTable);
                nsMan.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512");
                nsMan.AddNamespace("saml2", "urn:oasis:names:tc:SAML:2.0:assertion");
                var parentNodes   = "trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/";
                var assertionNode = xmlDoc.SelectSingleNode(parentNodes + "saml2:EncryptedAssertion", nsMan);
                if (assertionNode == null)
                {
                    assertionNode = xmlDoc.SelectSingleNode(parentNodes + "saml2:Assertion", nsMan);
                }
                else
                {
                    //this is an encrypted response so add a ServiceTokenResolver of X509CertificateStoreTokenResolver so the assertion can be decrypted. Hard codes LocalMachine - could be configured as well.
                    config.ServiceTokenResolver = new X509CertificateStoreTokenResolver(Options.EncryptionCertStoreName, StoreLocation.LocalMachine);
                }

                if (assertionNode == null)
                {
                    throw new Exception("No assertion element found in Response.");
                }

                using (var reader = new XmlNodeReader(assertionNode))
                {
                    //Get the token and convert it to a Claims Principal for return
                    SecurityTokenHandlerCollection collection = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);
                    var securityToken    = collection.ReadToken(reader);
                    var claimsIdentities = collection.ValidateToken(securityToken);

                    ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentities);
                    return(principal);
                }
            }
            catch (Exception ex)
            {
                //TODO: Add some logging
                var err = ex;
            }


            return(null);
        }
 public HttpsSecurityTokenHandler()
     : base(X509CertificateValidator.None)
 {
     Configuration = new SecurityTokenHandlerConfiguration
     {
         IssuerNameRegistry = new HttpsIssuerNameRegistry()
     };
 }
        private static SecurityTokenHandlerCollection CreateDefaultHandlerCollection(
            this SecurityTokenHandlerConfiguration configuration)
        {
            var handlerCollection =
                SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

            handlerCollection.AddOrReplace(new CustomSaml2SecurityTokenHandler());
            return(handlerCollection);
        }
Пример #19
0
        private ClaimsIdentity ValidateSamlToken(SecurityToken securityToken)
        {
            var configuration = new SecurityTokenHandlerConfiguration();
            var handler       = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

            handler.AddOrReplace(new CustomSaml2SecurityTokenHandler());
            var identity = handler.ValidateToken(securityToken).First();

            return(identity);
        }
Пример #20
0
        /// <summary>Turns a supported generic XML security token to a security token.</summary>
        /// <param name="token">The token.</param>
        /// <param name="decryptionCertificate">The decryption certificate.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token, X509Certificate2 decryptionCertificate)
        {
            var configuration = new SecurityTokenHandlerConfiguration();

            configuration.ServiceTokenResolver = decryptionCertificate.CreateSecurityTokenResolver();

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

            return(token.ToSecurityToken(handler));
        }
        /// <summary>Converts a SecurityToken to an IClaimsPrincipal.</summary>
        /// <param name="token">The token.</param>
        /// <param name="signingCertificate">The signing certificate.</param>
        /// <param name="audienceUri">The audience URI.</param>
        /// <returns>An IClaimsPrincipal</returns>
        public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, X509Certificate2 signingCertificate,
                                                        string audienceUri)
        {
            SecurityTokenHandlerConfiguration standardConfiguration = CreateStandardConfiguration(signingCertificate);

            standardConfiguration.AudienceRestriction.AudienceMode = AudienceUriMode.Always;
            standardConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUri));
            return(ToClaimsPrincipal(token,
                                     CreateDefaultHandlerCollection(standardConfiguration)));
        }
Пример #22
0
        private static SecurityTokenHandlerConfiguration CreateStandardConfiguration(X509Certificate2 signingCertificate)
        {
            var configuration = new SecurityTokenHandlerConfiguration();

            configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            configuration.IssuerNameRegistry   = signingCertificate.CreateIssuerNameRegistry();
            configuration.IssuerTokenResolver  = signingCertificate.CreateSecurityTokenResolver();
            configuration.SaveBootstrapContext = true;

            return(configuration);
        }
        public static void AddSaml11(this AuthenticationConfiguration configuration, SecurityTokenHandlerConfiguration handlerConfiguration, AuthenticationOptions options)
        {
            var handler = new HttpSamlSecurityTokenHandler();
            handler.Configuration = handlerConfiguration;

            configuration.AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection { handler },
                Options = options
            });
        }
Пример #24
0
        protected virtual SecurityTokenHandler GetSecurityTokenHandler()
        {
            var authPlugin = PluginManager.GetSingleton <SamlOAuthClient>();


            //var config = System.IdentityModel.Services.Configuration..FederationConfiguration..;
            SecurityTokenHandler handler   = null;
            var securityRequirements       = new SamlSecurityTokenRequirement();
            var securityTokenHandlerConfig = new SecurityTokenHandlerConfiguration();

            switch (authPlugin.IdpBindingType)
            {
            case SamlBinding.SAML11_POST:
                handler = new SamlSecurityTokenHandler(securityRequirements)
                {
                    Configuration = securityTokenHandlerConfig
                };
                break;

            case SamlBinding.SAML20_POST:
                handler = new SubjectConfirmationDataSaml2SecurityTokenHandler(securityRequirements, authPlugin.SubjectRecipientValidationMode)
                {
                    Configuration = securityTokenHandlerConfig
                };
                break;
            }

            if (handler == null)
            {
                throw new InvalidOperationException(
                          string.Format("No suitable token handler was loaded for the SAML binding type : {0}",
                                        tokenProcessorConfiguration.IdpBindingType));
            }


            handler.Configuration.IssuerNameRegistry = new CodeBasedIssuerNameRegistry(tokenProcessorConfiguration.TrustedIssuerThumbprint.Split(','));

            handler.Configuration.CertificateValidationMode = tokenProcessorConfiguration.CertificateValidationMode;

            if (typeof(SamlSecurityTokenHandler).IsAssignableFrom(handler.GetType()))
            {
                ((SamlSecurityTokenHandler)handler).CertificateValidator = GetCertificateValidator(handler.Configuration.CertificateValidationMode);
            }

            if (typeof(Saml2SecurityTokenHandler).IsAssignableFrom(handler.GetType()))
            {
                ((Saml2SecurityTokenHandler)handler).CertificateValidator = GetCertificateValidator(handler.Configuration.CertificateValidationMode);
            }


            handler.Configuration.AudienceRestriction.AudienceMode = System.IdentityModel.Selectors.AudienceUriMode.Never;

            return(handler);
        }
Пример #25
0
        private static SecurityTokenHandlerConfiguration CreateSaml2SecurityTokenHandlerConfiguration(string issuerThumbprint, string issuerName, string audienceUri, X509CertificateValidator certificateValidator)
        {
            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(issuerThumbprint, issuerName);

            var handlerConfig = new SecurityTokenHandlerConfiguration();
            handlerConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUri));
            handlerConfig.IssuerNameRegistry = registry;
            handlerConfig.CertificateValidator = certificateValidator;
            return handlerConfig;
        }
        public static void AddSaml2(this AuthenticationConfiguration configuration, string issuerThumbprint, string issuerName, string audienceUri, X509CertificateValidator certificateValidator, AuthenticationOptions options, AuthenticationScheme scheme)
        {
            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(issuerThumbprint, issuerName);

            var handlerConfig = new SecurityTokenHandlerConfiguration();
            handlerConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUri));
            handlerConfig.IssuerNameRegistry = registry;
            handlerConfig.CertificateValidator = certificateValidator;

            configuration.AddSaml2(handlerConfig, options, scheme);
        }
        private WebSecurityTokenHandlerCollectionManager SetupSecurityTokenHandler()
        {
            var manager = new WebSecurityTokenHandlerCollectionManager();

            #region Basic Authentication
            // basic authentication
            manager.AddBasicAuthenticationHandler((username, password) => username == password);
            
            // sample to use membership provider
            //manager.AddBasicAuthenticationHandler((username, password) => Membership.ValidateUser(username, password));
            #endregion
            
            #region SAML
            // SAML via ADFS
            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("d1 c5 b1 25 97 d0 36 94 65 1c e2 64 fe 48 06 01 35 f7 bd db", "ADFS");

            var adfsConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://" + Constants.WebHost + "/webservicesecurity/rest/"));
            adfsConfig.IssuerNameRegistry = registry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            // token decryption (read from config)
            adfsConfig.ServiceTokenResolver = IdentityModelConfiguration.ServiceConfiguration.CreateAggregateTokenResolver();
            
            manager.AddSaml11SecurityTokenHandler("SAML", adfsConfig);
            //manager.AddSaml2SecurityTokenHandler("SAML", adfsConfig);
            
            #endregion

            #region ACS SWT
            manager.AddSimpleWebTokenHandler(
                "ACS",
                "https://" + Constants.ACS + "/",
                "https://" + Constants.WebHost + "/webservicesecurity/rest/",
                "ds9t7JPEsprLRxWvnFjGr+xOhWOy5H8ZHEr5z/rJbi8=");
            #endregion

            #region IdSrv SWT
            manager.AddSimpleWebTokenHandler(
                "IdSrv",
                "http://identity.thinktecture.com/trust",
                "https://" + Constants.WebHost + "/webservicesecurity/rest/",
                "yM7+ti12DiFWcg8t5EfdQbOIgdZCchkETYSXxmvTY0s=");
            #endregion

            #region Allow ASP.NET based authentication
            manager.AddDefaultHandler();
            #endregion

            return manager;
        }
        public Saml2PSecurityTokenHandler(SPOptions spOptions)
        {
            if (spOptions == null)
            {
                throw new ArgumentNullException(nameof(spOptions));
            }

            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerNameRegistry   = new ReturnRequestedIssuerNameRegistry(),
                AudienceRestriction  = GetAudienceRestriction(spOptions),
                SaveBootstrapContext = spOptions.SystemIdentityModelIdentityConfiguration.SaveBootstrapContext
            };
        }
Пример #29
0
        private static SecurityTokenHandlerConfiguration CreateStandardConfiguration(string thumbprint)
        {
            var configuration = new SecurityTokenHandlerConfiguration();

            configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

            var registry = new ConfigurationBasedIssuerNameRegistry();

            registry.AddTrustedIssuer(thumbprint, thumbprint);
            configuration.IssuerNameRegistry  = registry;
            configuration.SaveBootstrapTokens = true;

            return(configuration);
        }
        public void AddSaml2(SecurityTokenHandlerConfiguration configuration, AuthenticationOptions options)
        {
            var handler = new HttpSaml2SecurityTokenHandler();

            handler.Configuration = configuration;

            AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection {
                    handler
                },
                Options = options
            });
        }
Пример #31
0
        public SecurityTokenHandlerConfiguration GetConfiguration()
        {
            var inner         = new X509CertificateStoreTokenResolver("testCertStore", StoreLocation.LocalMachine);
            var tokenResolver = new IssuerTokenResolver(inner);
            var configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerTokenResolver       = tokenResolver,
                ServiceTokenResolver      = inner,
                AudienceRestriction       = new AudienceRestriction(AudienceUriMode.Always),
                CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.Custom,
            };

            return(configuration);
        }
        public ClientCertificateHandler(ClientCertificateMode mode, params string[] values)
        {
            X509CertificateValidator validator;
            ClientCertificateIssuerNameRegistry registry;

            // set validator and registry
            if (mode == ClientCertificateMode.ChainValidation)
            {
                validator = X509CertificateValidator.ChainTrust;
                registry = new ClientCertificateIssuerNameRegistry(false, mode);
            }
            if (mode == ClientCertificateMode.ChainValidationWithIssuerSubjectName ||
                mode == ClientCertificateMode.ChainValidationWithIssuerThumbprint)
            {
                validator = X509CertificateValidator.ChainTrust;
                registry = new ClientCertificateIssuerNameRegistry(true, mode, values);
            }
            else if (mode == ClientCertificateMode.PeerValidation)
            {
                validator = X509CertificateValidator.PeerTrust;
                registry = new ClientCertificateIssuerNameRegistry(false, mode);
            }
            else if (mode == ClientCertificateMode.IssuerThumbprint)
            {
                validator = X509CertificateValidator.None;
                registry = new ClientCertificateIssuerNameRegistry(true, mode, values);
            }
            else
            {
                throw new ArgumentException("mode");
            }

            Configuration = new SecurityTokenHandlerConfiguration
            {
                //CertificateValidationMode = X509CertificateValidationMode.Custom,
                CertificateValidator = validator,
                IssuerNameRegistry = registry
            };
        }
        public void AddSimpleWebToken(string issuer, string audience, string signingKey, AuthenticationOptions options)
        {
            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer(issuer, issuer);
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey(issuer, signingKey);
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience));

            var handler = new SimpleWebTokenHandler();
            handler.Configuration = config;

            AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection { handler },
                Options = options
            });
        }
        public void AddSaml11(SecurityTokenHandlerConfiguration configuration, AuthenticationOptions options)
        {
            var handler = new HttpSamlSecurityTokenHandler();
            handler.Configuration = configuration;

            AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection { handler },
                Options = options
            });
        }
        public void ManualWriteRoundtripDuplicateClaimTypes()
        {
            var signinKey = SymmetricKeyGenerator.Create(32);

            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256,
                    SigningCredentials = new HmacSigningCredentials(signinKey)
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 50000000000,
            };

            jwt.AddClaim(ClaimTypes.Name, "dominick");
            jwt.AddClaim(ClaimTypes.Email, "*****@*****.**");
            jwt.AddClaim(ClaimTypes.Role, "bar");
            jwt.AddClaim(ClaimTypes.Role, "foo");


            var handler = new JsonWebTokenHandler();
            var token = handler.WriteToken(jwt);
            Trace.WriteLine(token);

            // token should not be empty
            Assert.IsTrue(!string.IsNullOrWhiteSpace(token));

            // token with signature needs to be 3 parts
            var parts = token.Split('.');
            Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts");

            // signature must be 256 bits
            var sig = Base64Url.Decode(parts[2]);
            Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits");

            var jwtToken = handler.ReadToken(token);


            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("dominick", "dominick");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey));
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com"));

            handler.Configuration = config;
            var identity = handler.ValidateToken(jwtToken).First();

            Assert.IsTrue(identity.Claims.Count() == 4);
            Assert.IsTrue(identity.Claims.First().Issuer == "dominick");
        }
        private AuthenticationConfiguration ConfigureAuthentication()
        {
            var config = new AuthenticationConfiguration
            {
                // sample claims transformation for consultants sample, comment out to see raw claims
                ClaimsAuthenticationManager = new ConsultantsClaimsTransformer(),

                // value of the www-authenticate header, if not set, the first scheme added to the handler collection is used
                DefaultAuthenticationScheme = "Basic"
            };

            #region Basic Authentication
            config.Handler.AddBasicAuthenticationHandler((username, password) => username == password);
            #endregion

            #region IdSrv Simple Web Tokens
            config.Handler.AddSimpleWebTokenHandler(
                "IdSrv",
                "http://identity.thinktecture.com/trust",
                Constants.Realm,
                "Dc9Mpi3jbooUpBQpB/4R7XtUsa3D/ALSjTVvK8IUZbg=");
            #endregion

            #region ACS Simple Web Tokens
            config.Handler.AddSimpleWebTokenHandler(
                "ACS",
                "https://" + Constants.ACS + "/",
                Constants.Realm,
                "yFvxu8Xkmo/xBSSPrzqZLSAiB4lgjR4PIi0Bn1RsUDI=");
            #endregion

            #region ADFS SAML tokens
            // SAML via ADFS
            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("d1 c5 b1 25 97 d0 36 94 65 1c e2 64 fe 48 06 01 35 f7 bd db", "ADFS");

            var adfsConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            adfsConfig.IssuerNameRegistry = registry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            // token decryption (read from configuration section)
            adfsConfig.ServiceTokenResolver = FederatedAuthentication.ServiceConfiguration.CreateAggregateTokenResolver();

            config.Handler.AddSaml11SecurityTokenHandler("AdfsSaml", adfsConfig);
            //manager.AddSaml2SecurityTokenHandler("AdfsSaml", adfsConfig);

            #endregion

            #region IdSrv SAML tokens
            // SAML via IdSrv
            var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("A1EED7897E55388FCE60FEF1A1EED81FF1CBAEC6", "Thinktecture IdSrv");

            var idsrvConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            adfsConfig.IssuerNameRegistry = registry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            // token decryption (read from configuration section)
            adfsConfig.ServiceTokenResolver = FederatedAuthentication.ServiceConfiguration.CreateAggregateTokenResolver();

            config.Handler.AddSaml2SecurityTokenHandler("IdSrvSaml", adfsConfig);

            #endregion

            return config;
        }
 public HttpSaml2SecurityTokenHandler(SecurityTokenHandlerConfiguration configuration)
     : base()
 {
     Configuration = configuration;
 }
        private static AuthenticationConfiguration ConfigureAuthentication()
        {
            var config = new AuthenticationConfiguration();
            config.ClaimsAuthenticationManager = new ConsultantsClaimsTransformer();

            #region Basic Authentication
            config.Handler.AddBasicAuthenticationHandler((username, password) => username == password);
            #endregion

            #region IdSrv Simple Web Tokens
            config.Handler.AddSimpleWebTokenHandler(
                "IdSrv",
                "http://identity.thinktecture.com/trust",
                Thinktecture.Samples.Constants.Realm,
                "Dc9Mpi3jbooUpBQpB/4R7XtUsa3D/ALSjTVvK8IUZbg=");
            #endregion

            #region ACS Simple Web Tokens
            config.Handler.AddSimpleWebTokenHandler(
                "ACS",
                "https://" + Thinktecture.Samples.Constants.ACS + "/",
                Thinktecture.Samples.Constants.Realm,
                "yFvxu8Xkmo/xBSSPrzqZLSAiB4lgjR4PIi0Bn1RsUDI=");
            #endregion

            #region ADFS SAML tokens
            // SAML via ADFS
            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("d1 c5 b1 25 97 d0 36 94 65 1c e2 64 fe 48 06 01 35 f7 bd db", "ADFS");

            var adfsConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Thinktecture.Samples.Constants.Realm));
            adfsConfig.IssuerNameRegistry = registry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            // token decryption (read from configuration section)
            adfsConfig.ServiceTokenResolver = FederatedAuthentication.ServiceConfiguration.CreateAggregateTokenResolver();

            config.Handler.AddSaml11SecurityTokenHandler("AdfsSaml", adfsConfig);
            //manager.AddSaml2SecurityTokenHandler("AdfsSaml", adfsConfig);

            #endregion

            #region IdSrv SAML tokens
            // SAML via IdSrv
            var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("CD638612A35CD2F9232ECE36226B731FC666EF07", "Thinktecture IdSrv");

            var idsrvConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Thinktecture.Samples.Constants.Realm));
            adfsConfig.IssuerNameRegistry = registry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            // token decryption (read from configuration section)
            adfsConfig.ServiceTokenResolver = FederatedAuthentication.ServiceConfiguration.CreateAggregateTokenResolver();

            config.Handler.AddSaml2SecurityTokenHandler("IdSrvSaml", adfsConfig);

            #endregion

            return config;
        }
 public WebSaml11SecurityTokenHandler(SecurityTokenHandlerConfiguration configuration) 
     : base()
 {
     Configuration = configuration;
 }
        public void HandlerCreateRoundtripSingleClaimTypes()
        {
            var signinKey = SymmetricKeyGenerator.Create(32);

            var identity = new ClaimsIdentity(new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "*****@*****.**"),
                }, "Custom");

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = identity,
                SigningCredentials = new HmacSigningCredentials(signinKey),
                TokenIssuerName = "dominick",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(8)),
                AppliesToAddress = "http://foo.com"
            };

            var handler = new JsonWebTokenHandler();
            var token = handler.CreateToken(descriptor);


            var tokenString = handler.WriteToken(token);
            Trace.WriteLine(tokenString);

            // token should not be empty
            Assert.IsTrue(!string.IsNullOrWhiteSpace(tokenString));

            // token with signature needs to be 3 parts
            var parts = tokenString.Split('.');
            Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts");

            // signature must be 256 bits
            var sig = Base64Url.Decode(parts[2]);
            Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits");

            var jwtToken = handler.ReadToken(tokenString);


            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("dominick", "dominick");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey));
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com"));

            handler.Configuration = config;
            var identity2 = handler.ValidateToken(jwtToken).First();

            Assert.IsTrue(identity.Claims.Count() == 2);
            //Assert.IsTrue(identity.Claims.First().Issuer == "dominick");
        }