private static AuthenticationHandler GetDefaultAuthenticationHandler()
        {
            var authConfig = new AuthenticationConfiguration();

            #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"));
            #endregion

            var authHandler = new AuthenticationHandler(authConfig);
            return authHandler;
        }
        public void ValidUserNameCredentialWithTokenValidation()
        {
            var client = new OAuth2Client(new Uri(baseAddress));

            var response = client.RequestAccessTokenUserName(
                Constants.Credentials.ValidUserName,
                Constants.Credentials.ValidPassword,
                scope);

            Assert.IsTrue(response != null, "response is null");
            Assert.IsTrue(!string.IsNullOrWhiteSpace(response.AccessToken), "access token is null");
            Assert.IsTrue(!string.IsNullOrWhiteSpace(response.TokenType), "token type is null");
            Assert.IsTrue(response.ExpiresIn > 0, "expiresIn is 0");

            Trace.WriteLine(response.AccessToken);

            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("http://identityserver45.thinktecture.com/trust/changethis", "http://identityserver45.thinktecture.com/trust/initial");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("http://identityserver45.thinktecture.com/trust/changethis", "3ihK5qGVhp8ptIk9+TDucXQW4Aaengg3d5m6gU8nzc8=");
            config.IssuerTokenResolver = issuerResolver;

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

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

            var jwt = handler.ReadToken(response.AccessToken);

            var id = handler.ValidateToken(jwt);
        }
        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);
            }
        }
        public ClaimsPrincipal Validate(string userName, string password)
        {
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var credentials = new ClientCredentials();
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;

            GenericXmlSecurityToken genericToken;
            genericToken = WSTrustClient.Issue(
                new EndpointAddress(_address),
                new EndpointAddress(_realm),
                binding,
                credentials) as GenericXmlSecurityToken;

            var config = new SecurityTokenHandlerConfiguration();
            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(_realm));

            config.CertificateValidationMode = X509CertificateValidationMode.None;
            config.CertificateValidator = X509CertificateValidator.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(_issuerThumbprint, _address);
            config.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);

            ClaimsPrincipal principal;
            var token = genericToken.ToSecurityToken();
            principal = new ClaimsPrincipal(handler.ValidateToken(token));

            Tracing.Information("Successfully requested token for user via WS-Trust");
            return FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate("ResourceOwnerPasswordValidation", principal);
        }
 public HttpsSecurityTokenHandler()
     : base(X509CertificateValidator.None)
 {
     Configuration = new SecurityTokenHandlerConfiguration
     {
         IssuerNameRegistry = new HttpsIssuerNameRegistry()
     };
 }
예제 #6
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);
        }
        public void AddSaml2SecurityTokenHandler(string scheme, SecurityTokenHandlerConfiguration configuration)
        {
            var collection = new SecurityTokenHandlerCollection(configuration)
            {
                new HttpSaml2SecurityTokenHandler()
            };

            Add(scheme, collection);
        }
        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");
        }
        public void AddSaml11SecurityTokenHandler(string scheme, SecurityTokenHandlerConfiguration configuration)
        {
            var collection = new SecurityTokenHandlerCollection(configuration)
            {
                new WebSaml11SecurityTokenHandler(),
                new EncryptedSecurityTokenHandler()
            };

            Add(scheme, collection);
        }
예제 #10
0
파일: Login.ashx.cs 프로젝트: woloski/JabbR
 private static SecurityTokenHandlerCollection CreateSecurityTokenHandlerCollection(IApplicationSettings settings)
 {
     var config = new SecurityTokenHandlerConfiguration();
     config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(settings.FedAuthRealm));
     config.CertificateValidator = X509CertificateValidator.None;
     config.IssuerNameRegistry = new CustomIssuerNameRegistry(settings.FedAuthCertificateThumbprint);
     var handlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);
     handlers.AddOrReplace(new MachineKeySessionSecurityTokenHandler());
     return handlers;
 }
        private static void ConfigureHandler(SecurityTokenHandlerConfiguration configuration)
        {
            var issuerTokens = new List<SecurityToken> { new X509SecurityToken(GetSigningCertificate()) }.AsReadOnly();
            configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                issuerTokens, false);

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(GetSigningCertificate().Thumbprint, "TecTeacher");
            configuration.IssuerNameRegistry = registry;
        }
        /// <summary>
        /// Creates an instance of <see cref="SecurityTokenHandlerCollection"/>.
        /// Creates an empty set.
        /// </summary>
        /// <param name="configuration">The configuration to associate with the collection.</param>
        public SecurityTokenHandlerCollection(SecurityTokenHandlerConfiguration configuration)
        {
            if (configuration == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("configuration");
            }

            this.configuration     = configuration;
            this.keyInfoSerializer = new KeyInfoSerializer(true);
        }
 public Saml2AssertionFactory(ISaml2AssertionValidationOptions options)
 {
     if (options.Audience == null)
         throw new ArgumentNullException("Audience");
     if (options.Recipient == null)
         throw new ArgumentNullException("Recipient");
     if (options.Certificate == null)
         throw new ArgumentNullException("certificate");
     configuration = GetSecurityTokenHandlerConfiguration(options);
     tokenHandler = new Saml2BearerGrantSecurityTokenHandler(options.Recipient);
     tokenHandler.Configuration = configuration;
 }
예제 #14
0
        private static SecurityTokenHandlerCollection CreateSecurityTokenHandlerCollection(string realm, string thumbprint)
        {
            var config = new SecurityTokenHandlerConfiguration();
            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(realm));
            config.CertificateValidator = X509CertificateValidator.None;
            config.IssuerNameRegistry = new CustomIssuerNameRegistry(thumbprint);
            var handlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);
            handlers.AddOrReplace(new MachineKeySessionSecurityTokenHandler());
            FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(new MachineKeySessionSecurityTokenHandler());

            return handlers;
        }
 public CustomSaml2SecurityTokenHandler()
 {
     var registry = new ConfigurationBasedIssuerNameRegistry();
     registry.AddTrustedIssuer("fb369e5dcf3ae82dcbe95a922baff3112fcde352", "McKesson");
     registry.AddTrustedIssuer("17bfb6a73bc53bbfdc64e4e64f77b206471e9c08","Cerner");
     var handlerConfig = new SecurityTokenHandlerConfiguration
         {
             AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never),
             MaxClockSkew = new TimeSpan(50000000),
             IssuerNameRegistry = registry
         };
     Configuration = handlerConfig;
 }
        public Saml2PSecurityTokenHandler(ISPOptions spOptions)
        {
            if (spOptions == null)
            {
                throw new ArgumentNullException(nameof(spOptions));
            }

            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerNameRegistry = new ReturnRequestedIssuerNameRegistry(),
                AudienceRestriction = GetAudienceRestriction(spOptions),
                SaveBootstrapContext = spOptions.SystemIdentityModelIdentityConfiguration.SaveBootstrapContext
            };
        }
 public CustomSaml2SecurityTokenHandler()
 {
     var registry = new TrustedIssuerNameRegistry();
     var handlerConfig = new SecurityTokenHandlerConfiguration
     {
         AudienceRestriction = {AudienceMode = AudienceUriMode.Never},
         CertificateValidationMode = X509CertificateValidationMode.None,
         RevocationMode = X509RevocationMode.NoCheck,
         MaxClockSkew = new TimeSpan(50000000),
         IssuerNameRegistry = registry,
         CertificateValidator = X509CertificateValidator.None
     };
     Configuration = handlerConfig;
 }
        public Saml2PSecurityTokenHandler(ISPOptions spOptions)
        {
            if(spOptions== null)
            {
                throw new ArgumentNullException(nameof(spOptions));
            }

            var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);
            audienceRestriction.AllowedAudienceUris.Add(
                new Uri(spOptions.EntityId.Id));

            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerNameRegistry = new ReturnRequestedIssuerNameRegistry(),
                AudienceRestriction = audienceRestriction,
                SaveBootstrapContext = spOptions.SystemIdentityModelIdentityConfiguration.SaveBootstrapContext
            };
        }
        private static void ConfigureHandler(SecurityTokenHandler handler, Uri audience, string issuerThumbprint, string issuerName = null, X509CertificateValidator validator = null)
        {
            var handlerConfiguration = new SecurityTokenHandlerConfiguration();
            handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Add(audience);

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(issuerThumbprint, issuerName ?? issuerThumbprint);

            if (validator != null)
            {
                handlerConfiguration.CertificateValidator = validator;
            }
            else
            {
                handlerConfiguration.CertificateValidator = X509CertificateValidator.None;
            }

            handlerConfiguration.IssuerNameRegistry = registry;
            handler.Configuration = handlerConfiguration;
        }
예제 #20
0
        private static AuthenticationConfiguration CreateAuthenticationConfiguration()
        {
            var options = new AuthenticationOptions()
            {
                RequestType = HttpRequestType.AuthorizationHeader,
                Name = "Authorization",
                Scheme = "SAML"
            };

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer("18145fb6b5d96b3cc34ec7599f12172bb93c68ef", "DummySTS");

            var adfsConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri("urn:claimsdemo:mvc5http"));
            adfsConfig.IssuerNameRegistry = registry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificates = store.Certificates;
            X509Certificate2Collection matchingCertificates = certificates.Find(
                X509FindType.FindByThumbprint,
                "a2028f8e7f7b082cd35e81fd0ca0b70b04651abf", false);
            X509Certificate2 certificate = certificates[0];

            List<SecurityToken> serviceTokens = new List<SecurityToken>();
            serviceTokens.Add(new X509SecurityToken(certificate));
            SecurityTokenResolver serviceResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                    serviceTokens.AsReadOnly(), false);
            adfsConfig.ServiceTokenResolver = serviceResolver;

            var config = new AuthenticationConfiguration
            {
                RequireSsl = false
            };

            config.AddSaml11(adfsConfig, options);

            return config;
        }
        public ClaimsIdentity ValidateSamlToken(GenericXmlSecurityToken securityToken)
        {
            var _handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
            var tokenString = securityToken.ToTokenXmlString();

            var samlToken2 = _handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            var configuration = new SecurityTokenHandlerConfiguration();
            configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            configuration.CertificateValidationMode = X509CertificateValidationMode.None;
            configuration.RevocationMode = X509RevocationMode.NoCheck;
            configuration.CertificateValidator = X509CertificateValidator.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(trustedIssuerCertificateThumbPrint, trustedIssuerName);
            configuration.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
            var identity = handler.ValidateToken(samlToken2).First();
            return identity;
        }
        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);
            }
            else 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 static void AddJsonWebToken(this AuthenticationConfiguration configuration, 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;

            configuration.AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection { handler },
                Options = options
            });
        }
        private static AuthenticationHandler GetDefaultAuthenticationHandler()
        {
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false
            };

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

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

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

            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();

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

            #endregion

            var authHandler = new AuthenticationHandler(authConfig);
            return authHandler;
        }
        public void AddSimpleWebTokenHandler(string scheme, string issuer, string audience, string signingKey)
        {
            var config = new SecurityTokenHandlerConfiguration();

            // issuer name registry
            var registry = new SymmetricSigningKeyIssuerNameRegistry();
            registry.AddTrustedIssuer(issuer, issuer);
            config.IssuerNameRegistry = registry;

            // issuer signing key resolver
            var issuerResolver = new SymmetricSigningKeyIssuerTokenResolver();
            issuerResolver.AddSigningKey(issuer, signingKey);
            config.IssuerTokenResolver = issuerResolver;

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

            var collection = new SecurityTokenHandlerCollection(config)
            {
                new SwtSecurityTokenHandler()
            };

            Add(scheme, collection);
        }
        protected virtual SecurityTokenHandlerConfiguration GetSecurityTokenHandlerConfiguration(ISaml2AssertionValidationOptions options)
        {
            var serviceTokens = new List<SecurityToken>();
            serviceTokens.Add(new X509SecurityToken(options.Certificate));

            var issuers = new ConfigurationBasedIssuerNameRegistry();
            issuers.AddTrustedIssuer(options.Certificate.Thumbprint, options.Certificate.Issuer);

            var conf = new SecurityTokenHandlerConfiguration
            {
                AudienceRestriction = new AudienceRestriction(AudienceUriMode.Always),
                CertificateValidator = X509CertificateValidator.ChainTrust,
                RevocationMode = X509RevocationMode.NoCheck,
                IssuerNameRegistry = issuers,
                MaxClockSkew = TimeSpan.FromMinutes(5),
                ServiceTokenResolver =
                    SecurityTokenResolver.CreateDefaultSecurityTokenResolver(serviceTokens.AsReadOnly(), false)
            };
            foreach (var y in options.Audience)
            {
                conf.AudienceRestriction.AllowedAudienceUris.Add(y);
            }
            return conf;
        }
        /// <summary>
        /// Creates a system default collection of basic SecurityTokenHandlers, each of which has the system default configuration.
        /// The SecurityTokenHandlers in this collection must be configured with service specific data before they can be used.
        /// </summary>
        /// <param name="configuration">The configuration to associate with the collection.</param>
        /// <returns>A SecurityTokenHandlerCollection with default basic SecurityTokenHandlers.</returns>
        public static SecurityTokenHandlerCollection CreateDefaultSecurityTokenHandlerCollection(SecurityTokenHandlerConfiguration configuration)
        {
            SecurityTokenHandlerCollection collection = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] {
                new KerberosSecurityTokenHandler(),
                new RsaSecurityTokenHandler(),
                new SamlSecurityTokenHandler(),
                new Saml2SecurityTokenHandler(),
                new WindowsUserNameSecurityTokenHandler(),
                new X509SecurityTokenHandler(),
                new EncryptedSecurityTokenHandler(),
                new SessionSecurityTokenHandler(),
            },
                                                                                           configuration);

            defaultHandlerCollectionCount = collection.Count;

            return(collection);
        }
        /// <summary>
        /// Creates an instance of <see cref="SecurityTokenHandlerCollection"/>
        /// </summary>
        /// <param name="handlers">List of SecurityTokenHandlers to initialize from.</param>
        /// <param name="configuration">The <see cref="SecurityTokenHandlerConfiguration"/> in effect.</param>
        /// <remarks>
        /// Do not use this constructor to attempt to clone an instance of a SecurityTokenHandlerCollection,
        /// use the Clone method instead.
        /// </remarks>
        public SecurityTokenHandlerCollection(IEnumerable <SecurityTokenHandler> handlers, SecurityTokenHandlerConfiguration configuration)
            : this(configuration)
        {
            if (handlers == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("handlers");
            }

            foreach (SecurityTokenHandler handler in handlers)
            {
                Add(handler);
            }
        }
예제 #29
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 AuthenticationConfiguration CreateConfiguration()
        {
            var config = new AuthenticationConfiguration
            {
                DefaultAuthenticationScheme = "Basic",
                EnableSessionToken = true
            };

            #region BasicAuthentication
            config.AddBasicAuthentication((userName, password) => userName == password, retainPassword: false);
            #endregion

            #region SimpleWebToken
            config.AddSimpleWebToken(
                issuer: "http://identity.thinktecture.com/trust",
                audience: Constants.Realm,
                signingKey: Constants.IdSrvSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("IdSrv"));
            #endregion

            #region JsonWebToken
            config.AddJsonWebToken(
                issuer: "http://selfissued.test",
                audience: Constants.Realm,
                signingKey: Constants.IdSrvSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("JWT"));
            #endregion

            #region IdentityServer SAML
            var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry();
            idsrvRegistry.AddTrustedIssuer("A1EED7897E55388FCE60FEF1A1EED81FF1CBAEC6", "Thinktecture IdSrv");

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

            config.AddSaml2(idsrvConfig, AuthenticationOptions.ForAuthorizationHeader("IdSrvSaml"));
            #endregion

            #region ADFS SAML
            var adfsRegistry = new ConfigurationBasedIssuerNameRegistry();
            adfsRegistry.AddTrustedIssuer("8EC7F962CC083FF7C5997D8A4D5ED64B12E4C174", "ADFS");
            adfsRegistry.AddTrustedIssuer("b6 93 46 34 7f 70 a9 c3 72 02 18 ae f1 82 2a 5c 97 b1 8c a5", "PETS ADFS");

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

            config.AddSaml2(adfsConfig, AuthenticationOptions.ForAuthorizationHeader("AdfsSaml"));
            #endregion

            #region ACS SWT
            config.AddSimpleWebToken(
                issuer: "https://" + Constants.ACS + "/",
                audience: Constants.Realm,
                signingKey: Constants.AcsSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("ACS"));
            #endregion

            #region AccessKey
            config.AddAccessKey(token =>
            {
                if (ObfuscatingComparer.IsEqual(token, "accesskey123"))
                {
                    return Principal.Create("Custom",
                        new Claim("customerid", "123"),
                        new Claim("email", "*****@*****.**"));
                }

                return null;
            }, AuthenticationOptions.ForQueryString("key"));
            #endregion

            #region Client Certificate
            config.AddClientCertificate(
                ClientCertificateMode.ChainValidationWithIssuerSubjectName, 
                "CN=PortableCA");
            #endregion

            return config;
        }
        private ClaimsPrincipal ValidateToken(SecurityToken token)
        {
            var config = new SecurityTokenHandlerConfiguration();
            config.AudienceRestriction.AudienceMode = AudienceUriMode.Always;
            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(ConfigurationRepository.Global.IssuerUri));
            
            var registry = new IdentityProviderIssuerNameRegistry(GetEnabledWSIdentityProviders());
            config.IssuerNameRegistry = registry;
            config.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            config.CertificateValidator = X509CertificateValidator.None;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);
            var identity = handler.ValidateToken(token).First();

            return new ClaimsPrincipal(identity);
        }
        /// <summary>
        /// Loads configuration elements pertaining to the <see cref="SecurityTokenHandlerCollection"/>
        /// </summary>
        /// <param name="baseConfiguration">Base <see cref="SecurityTokenHandlerConfiguration"/> from which to inherit default values.</param>
        /// <param name="element">The <see cref="SecurityTokenHandlerConfigurationElement"/> from the configuration file.</param>
        /// <returns></returns>
        protected SecurityTokenHandlerConfiguration LoadHandlerConfiguration(SecurityTokenHandlerConfiguration baseConfiguration, SecurityTokenHandlerConfigurationElement element)
        {
            SecurityTokenHandlerConfiguration handlerConfiguration = (baseConfiguration == null) ? new SecurityTokenHandlerConfiguration() : baseConfiguration;

            if (element.AudienceUris.IsConfigured)
            {
                //
                // There is no inheritance of the content of the element from base to child, only the whole element. If the
                // user specifies any part, they must specify it all.
                //
                handlerConfiguration.AudienceRestriction.AudienceMode = AudienceUriMode.Always;
                handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Clear();

                handlerConfiguration.AudienceRestriction.AudienceMode = element.AudienceUris.Mode;

                foreach (AudienceUriElement audienceUriElement in element.AudienceUris)
                {
                    handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUriElement.Value, UriKind.RelativeOrAbsolute));
                }
            }

            if (element.Caches.IsConfigured)
            {
                if (element.Caches.TokenReplayCache.IsConfigured)
                {
                    handlerConfiguration.Caches.TokenReplayCache = CustomTypeElement.Resolve<TokenReplayCache>(element.Caches.TokenReplayCache);
                }

                if (element.Caches.SessionSecurityTokenCache.IsConfigured)
                {
                    handlerConfiguration.Caches.SessionSecurityTokenCache = CustomTypeElement.Resolve<SessionSecurityTokenCache>(element.Caches.SessionSecurityTokenCache);
                }
            }

            if (element.CertificateValidation.IsConfigured)
            {
                handlerConfiguration.RevocationMode = element.CertificateValidation.RevocationMode;
                handlerConfiguration.CertificateValidationMode = element.CertificateValidation.CertificateValidationMode;
                handlerConfiguration.TrustedStoreLocation = element.CertificateValidation.TrustedStoreLocation;

                if (element.CertificateValidation.CertificateValidator.IsConfigured)
                {
                    handlerConfiguration.CertificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(element.CertificateValidation.CertificateValidator);
                }
            }

            //
            // Load the issuer name registry
            //
            if (element.IssuerNameRegistry.IsConfigured)
            {
                handlerConfiguration.IssuerNameRegistry = GetIssuerNameRegistry(element.IssuerNameRegistry);
            }

            //
            // Load the issuer token resolver
            //
            if (element.IssuerTokenResolver.IsConfigured)
            {
                handlerConfiguration.IssuerTokenResolver = CustomTypeElement.Resolve<SecurityTokenResolver>(element.IssuerTokenResolver);
            }

            //
            // Load MaxClockSkew
            //
            try
            {
                if (element.ElementInformation.Properties[ConfigurationStrings.MaximumClockSkew].ValueOrigin != PropertyValueOrigin.Default)
                {
                    handlerConfiguration.MaxClockSkew = element.MaximumClockSkew;
                }
            }
            catch (ArgumentException inner)
            {
                throw DiagnosticUtility.ThrowHelperConfigurationError(element, ConfigurationStrings.MaximumClockSkew, inner);
            }

            //
            // SaveBootstrapTokens
            //
            if (element.ElementInformation.Properties[ConfigurationStrings.SaveBootstrapContext].ValueOrigin != PropertyValueOrigin.Default)
            {
                handlerConfiguration.SaveBootstrapContext = element.SaveBootstrapContext;
            }

            //
            // Load the service token resolver
            //
            if (element.ServiceTokenResolver.IsConfigured)
            {
                handlerConfiguration.ServiceTokenResolver = CustomTypeElement.Resolve<SecurityTokenResolver>(element.ServiceTokenResolver);
            }

            //
            // TokenReplayCache related items
            //
            if (element.TokenReplayDetection.IsConfigured)
            {
                //
                // Set on SecurityTokenHandlerConfiguration
                //

                //
                // DetectReplayedTokens set - { true | false }
                //
                handlerConfiguration.DetectReplayedTokens = element.TokenReplayDetection.Enabled;

                //
                // ExpirationPeriod { TimeSpan }
                //
                handlerConfiguration.TokenReplayCacheExpirationPeriod = element.TokenReplayDetection.ExpirationPeriod;

            }

            return handlerConfiguration;
        }
        /// <summary>
        /// Loads a SecurityTokenHandlerConfiguration using the elements directly under the ServiceElement.
        /// </summary>
        protected SecurityTokenHandlerConfiguration LoadHandlerConfiguration(IdentityConfigurationElement element)
        {

            SecurityTokenHandlerConfiguration handlerConfiguration = new SecurityTokenHandlerConfiguration();

            try
            {
                if (element.ElementInformation.Properties[ConfigurationStrings.MaximumClockSkew].ValueOrigin != PropertyValueOrigin.Default)
                {
                    handlerConfiguration.MaxClockSkew = element.MaximumClockSkew;
                }
                else
                {
                    handlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;
                }
            }
            catch (ArgumentException inner)
            {
                throw DiagnosticUtility.ThrowHelperConfigurationError(element, ConfigurationStrings.MaximumClockSkew, inner);
            }

            if (element.AudienceUris.IsConfigured)
            {
                handlerConfiguration.AudienceRestriction.AudienceMode = element.AudienceUris.Mode;

                foreach (AudienceUriElement audienceUriElement in element.AudienceUris)
                {
                    handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUriElement.Value, UriKind.RelativeOrAbsolute));
                }
            }
            if (element.Caches.IsConfigured)
            {
                if (element.Caches.TokenReplayCache.IsConfigured)
                {
                    handlerConfiguration.Caches.TokenReplayCache = CustomTypeElement.Resolve<TokenReplayCache>(element.Caches.TokenReplayCache);
                }

                if (element.Caches.SessionSecurityTokenCache.IsConfigured)
                {
                    handlerConfiguration.Caches.SessionSecurityTokenCache = CustomTypeElement.Resolve<SessionSecurityTokenCache>(element.Caches.SessionSecurityTokenCache);
                }
            }

            if (element.CertificateValidation.IsConfigured)
            {
                handlerConfiguration.RevocationMode = element.CertificateValidation.RevocationMode;
                handlerConfiguration.CertificateValidationMode = element.CertificateValidation.CertificateValidationMode;
                handlerConfiguration.TrustedStoreLocation = element.CertificateValidation.TrustedStoreLocation;

                if (element.CertificateValidation.CertificateValidator.IsConfigured)
                {
                    handlerConfiguration.CertificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(element.CertificateValidation.CertificateValidator);
                }
            }

            //
            // Load the issuer name registry
            //
            if (element.IssuerNameRegistry.IsConfigured)
            {
                handlerConfiguration.IssuerNameRegistry = GetIssuerNameRegistry(element.IssuerNameRegistry);
            }

            //
            // Load the issuer token resolver
            //
            if (element.IssuerTokenResolver.IsConfigured)
            {
                handlerConfiguration.IssuerTokenResolver = GetIssuerTokenResolver(element);
            }

            //
            // SaveBootstrapContext
            //
            handlerConfiguration.SaveBootstrapContext = element.SaveBootstrapContext;

            //
            // Load the service token resolver
            //
            if (element.ServiceTokenResolver.IsConfigured)
            {
                handlerConfiguration.ServiceTokenResolver = GetServiceTokenResolver(element);
            }

            //
            // TokenReplayCache related items
            //
            if (element.TokenReplayDetection.IsConfigured)
            {
                //
                // Set on SecurityTokenHandlerConfiguration
                //

                // DetectReplayedTokens set - { true | false }
                //
                handlerConfiguration.DetectReplayedTokens = element.TokenReplayDetection.Enabled;

                // ExpirationPeriod { TimeSpan }
                //
                handlerConfiguration.TokenReplayCacheExpirationPeriod = element.TokenReplayDetection.ExpirationPeriod;
            }

            return handlerConfiguration;
        }
예제 #34
0
 public SecurityTokenHandlerCollection(IEnumerable <SecurityTokenHandler> handlers, SecurityTokenHandlerConfiguration configuration) : this(configuration) {
     foreach (var handler in handlers)
     {
         Add(handler);
     }
 }
예제 #35
0
 public SecurityTokenHandlerCollection(SecurityTokenHandlerConfiguration configuration)
 {
     config = configuration;
 }
예제 #36
0
 public static SecurityTokenHandlerCollection CreateDefaultSecurityTokenHandlerCollection(SecurityTokenHandlerConfiguration configuration)
 {
     throw new NotImplementedException();
 }