Example #1
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;
            }
        }
Example #2
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));
            }
        }
        /// <summary>Turns a supported generic XML security token into a security token.</summary>
        /// <param name="token">The generic XML security token.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token)
        {
            SecurityTokenHandlerCollection handlerCollection =
                SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();

            return(token.ToSecurityToken(handlerCollection));
        }
Example #4
0
        public ActionResult MyToken()
        {
            var config      = ConfigurationRepository.Configuration;
            var samlHandler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection()[config.DefaultTokenType];

            var descriptor = new SecurityTokenDescriptor
            {
                AppliesToAddress   = "http://self",
                Lifetime           = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(config.DefaultTokenLifetime)),
                SigningCredentials = new X509SigningCredentials(ConfigurationRepository.SigningCertificate.Certificate),
                TokenIssuerName    = config.IssuerUri,
                Subject            = new ClaimsIdentity(GetClaims())
            };

            var token = samlHandler.CreateToken(descriptor);

            var sb = new StringBuilder(1024);

            samlHandler.WriteToken(XmlWriter.Create(new StringWriter(sb)), token);

            return(new ContentResult
            {
                ContentType = "text/xml",
                Content = sb.ToString()
            });
        }
Example #5
0
        protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString)
        {
            SecurityTokenHandler handler = null;

            if (handlers.Count == 1)
            {
                handler = handlers.First();
            }
            else
            {
                foreach (var h in handlers)
                {
                    if (((IHttpSecurityTokenHandler)h).CanReadToken(tokenString))
                    {
                        handler = h;
                        break;
                    }
                }
            }

            if (handler != null)
            {
                var token     = ((IHttpSecurityTokenHandler)handler).ReadToken(tokenString);
                var principal = new ClaimsPrincipal(handler.ValidateToken(token));

                return(principal);
            }

            throw new InvalidOperationException("No handler found");
        }
        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));
        }
        public void SecurityTokenHandlerCollectionExtensions_Publics()
        {
            SecurityTokenHandlerCollection securityTokenValidators = new SecurityTokenHandlerCollection();
            string defaultSamlToken  = IdentityUtilities.CreateSamlToken();
            string defaultSaml2Token = IdentityUtilities.CreateSaml2Token();
            string defaultJwt        = IdentityUtilities.DefaultAsymmetricJwt;

            ExpectedException expectedException = ExpectedException.ArgumentNullException("Parameter name: securityToken");

            ValidateToken(null, null, securityTokenValidators, expectedException);

            expectedException = ExpectedException.ArgumentNullException("Parameter name: validationParameters");
            ValidateToken(defaultSamlToken, null, securityTokenValidators, expectedException);

            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters();

            expectedException = ExpectedException.SecurityTokenValidationException("IDX10201");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            expectedException       = ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators.Clear();
            securityTokenValidators.Add(new IMSamlTokenHandler());
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:"));
            ValidateToken(defaultSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.SecurityTokenValidationException(substringExpected: "IDX10201:"));
            securityTokenValidators.Add(new IMSaml2TokenHandler());
            securityTokenValidators.Add(new System.IdentityModel.Tokens.JwtSecurityTokenHandler());
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultJwt, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
        }
Example #8
0
        protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString)
        {
            SecurityTokenHandler handler = null;

            if (handlers.Count == 1)
            {
                handler = handlers.First();
            }
            else
            {
                foreach (var h in handlers)
                {
                    if (h.CanReadToken(tokenString))
                    {
                        handler = h;
                        break;
                    }
                }
            }

            if (handler != null)
            {
                Tracing.Information("Invoking token handler: " + handler.GetType().FullName);

                var token     = handler.ReadToken(tokenString);
                var principal = new ClaimsPrincipal(handler.ValidateToken(token));

                return(principal);
            }

            throw new InvalidOperationException("No handler found");
        }
Example #9
0
        static void Main(string[] args)
        {
            // Create and setup the configuration for our STS
            SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("STS");

            // Add the STS endpoint information
            config.TrustEndpoints.Add(
                new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetSTSBinding(), "http://localhost:6000/STS"));

            // Set the STS implementation class type
            config.SecurityTokenService = typeof(CustomSecurityTokenService);
            SecurityTokenHandlerCollection actAsHandlerCollection = config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.ActAs];

            actAsHandlerCollection.Configuration.IssuerNameRegistry = new ActAsIssuerNameRegistry();
            // The token that we receive in the <RequestSecurityToken><ActAs> element was issued to the service proxies.
            // By adding the proxy audience URIs here we are enforcing the implicit contract that the STS will accept
            // only tokens issued to the proxy as an ActAs token.
            actAsHandlerCollection.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://localhost/WFE/default.aspx"));
            actAsHandlerCollection.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost/Service1/Service1.svc"));

            // Create the WS-Trust service host with our STS configuration
            using (WSTrustServiceHost host = new WSTrustServiceHost(config, new Uri("http://localhost:6000/STS")))
            {
                host.Open();

                Console.WriteLine("STS started, press ENTER to stop ...");
                Console.ReadLine();

                host.Close();
            }
        }
Example #10
0
 private static void LoginWithToken(AuthenticationHeaderValue credentials, SecurityTokenHandlerCollection handlers, HttpApplication context)
 {
     try
     {
         var token = Convert.FromBase64String(credentials.Parameter);
         using (var stream = new MemoryStream(token))
         {
             using (var xmlReader = XmlReader.Create(stream))
             {
                 var securityToken = handlers.ReadToken(xmlReader);
                 var identities    = handlers.ValidateToken(securityToken);
                 var principal     = new ClaimsPrincipal(identities);
                 var identity      = principal.Identity as ClaimsIdentity;
                 if (identity != null)
                 {
                     identity.BootstrapContext = new BootstrapContext(token);
                 }
                 Thread.CurrentPrincipal = principal;
                 context.Context.User    = principal;
             }
         }
     }
     catch (Exception)
     {
         context.Response.AppendHeader("X-InvalidCredentials", "token");
         throw;
     }
 }
        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));
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            // <!-- IssuerName Configuration - ha50idpm2 -->
            string idpEntityId = WebConfigurationManager.AppSettings["IdpEntityId"];
            CustomSecurityTokenServiceConfiguration config = new CustomSecurityTokenServiceConfiguration(idpEntityId);

            // Create a security token handler collection and then provide with a SAML2 security token
            // handler and set the Audience restriction to Never
            SecurityTokenHandlerCollection onBehalfOfHandlers = new SecurityTokenHandlerCollection();
            OnBehalfOfSaml2SecurityTokenHandler onBehalfOfTokenHandler = new OnBehalfOfSaml2SecurityTokenHandler();

            onBehalfOfHandlers.Add(onBehalfOfTokenHandler);

            // Do not process the Audience in the incoming OnBehalfOf token since this token
            // is not for authenticating with the ADS
            onBehalfOfHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

            // Set the appropriate issuer name registry
            onBehalfOfHandlers.Configuration.IssuerNameRegistry = new IdpAdsIssuerNameRegistry();

            // Set the token handlers collection
            config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf] = onBehalfOfHandlers;
            
            WSTrustServiceHost host = new WSTrustServiceHost(config, baseAddresses);

            host.Description.Endpoints[0].Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

            return host;
        }        
Example #13
0
        private static void TestCompressedToken(SecurityToken token)
        {
            var handlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();

            handlers.Add(new AccessSecurityTokenHandler());
            handlers.Add(new CompressedSecurityTokenHandler());

            ConfigureHandler(handlers.Configuration);

            var compressedToken = new CompressedSecurityToken(token);
            var sb = new StringBuilder();

            using (var writer = new XmlTextWriter(new StringWriter(sb)))
            {
                handlers.WriteToken(writer, compressedToken);
            }

            SecurityToken readToken;

            using (var reader = sb.ToString().AsXmlReader(true))
            {
                readToken = handlers.ReadToken(reader);
            }

            handlers.ValidateToken(readToken);
        }
            internal override void WriteTo(XmlWriter writer)
            {
                writer.WriteStartElement(ElementName);
                writer.WriteAttributeString(DiagnosticStrings.NamespaceTag, EventId);

                writer.WriteStartElement("SecurityToken");
                writer.WriteAttributeString("Type", _securityToken.GetType().ToString());

                if (_securityToken is SessionSecurityToken)
                {
                    WriteSessionToken(writer, _securityToken as SessionSecurityToken);
                }
                else
                {
                    SecurityTokenHandlerCollection sthc = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                    if (sthc.CanWriteToken(_securityToken))
                    {
                        {
                            sthc.WriteToken(writer, _securityToken);
                        }
                    }
                    else
                    {
                        writer.WriteElementString("Warning", SR.GetString(SR.TraceUnableToWriteToken, _securityToken.GetType().ToString()));
                    }
                }

                writer.WriteEndElement();
            }
        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 bool TryGetClientCertificateMapping(out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.ClientCertificate
                       select m.TokenHandler).SingleOrDefault();

            return(handler != null);
        }
Example #17
0
 private SecurityToken ReadSecurityToken(string tokenString, SecurityTokenHandlerCollection handlers)
 {
     using (var reader = new XmlTextReader(new StringReader(tokenString)))
     {
         var token = handlers.ReadToken(reader);
         return(token);
     }
 }
        public bool TryGetHeaderMapping(string headerName, out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.Header &&
                       m.Options.Name == headerName
                       select m.TokenHandler).SingleOrDefault();

            return(handler != null);
        }
        public void AddSaml2SecurityTokenHandler(string scheme, SecurityTokenHandlerConfiguration configuration)
        {
            var collection = new SecurityTokenHandlerCollection(configuration)
            {
                new HttpSaml2SecurityTokenHandler()
            };

            Add(scheme, collection);
        }
 public StartSaml2TokenSerializerAdapter(SecurityTokenHandlerCollection securityTokenHandlerCollection,
                                         SecurityVersion securityVersion)
     : base(securityTokenHandlerCollection, securityVersion)
 {
     samlHandler = new StartSaml2SecurityTokenHandler()
     {
         Configuration = securityTokenHandlerCollection.Configuration
     };
 }
        public bool TryGetQueryStringMapping(string paramName, out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.QueryString &&
                       m.Options.Name == paramName
                       select m.TokenHandler).SingleOrDefault();

            return(handler != null);
        }
        private static SecurityTokenHandlerCollection CreateDefaultHandlerCollection(
            this SecurityTokenHandlerConfiguration configuration)
        {
            var handlerCollection =
                SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

            handlerCollection.AddOrReplace(new CustomSaml2SecurityTokenHandler());
            return(handlerCollection);
        }
        public static void tokenTest()
        {
            string relyingPartyId         = "https://shadfs.sanfordhealth.org/adfs/ls/ldpinitiatedsignon.aspx";
            WSTrustChannelFactory factory = null;

            try
            {
                // use a UserName Trust Binding for username authentication
                factory = new WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    new EndpointAddress("https://secure.genomenext.net/app/services/trust/13/usernamemixed"));
                /////I'll change this endpoint this later////////

                factory.TrustVersion = TrustVersion.WSTrust13;

                factory.Credentials.UserName.UserName = "******";
                factory.Credentials.UserName.Password = "******";

                var rst = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(relyingPartyId),
                    KeyType     = KeyTypes.Bearer
                };
                IWSTrustChannelContract channel      = factory.CreateChannel();
                GenericXmlSecurityToken genericToken = channel.Issue(rst) as GenericXmlSecurityToken; //MessageSecurityException -> PW falsch

                var _handler    = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                var tokenString = genericToken.ToTokenXmlString();

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

                ValidateSamlToken(samlToken2);

                X509Certificate2 certificate = null;

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

                //  var jwt = ConvertSamlToJwt(samlToken2, "https://party.mycomp.com", certificate);
            }
            finally
            {
                if (factory != null)
                {
                    try
                    {
                        factory.Close();
                    }
                    catch (CommunicationObjectFaultedException)
                    {
                        factory.Abort();
                    }
                }
            }
Example #24
0
            private SecurityToken ReadToken(XmlReader reader)
            {
                SecurityTokenHandlerCollection securityTokenHandlers = this._serviceConfiguration.IdentityConfiguration.SecurityTokenHandlers;

                if (securityTokenHandlers.CanReadToken(reader))
                {
                    return(securityTokenHandlers.ReadToken(reader));
                }
                return(null);
            }
        public WsFederationAuthenticationOptions(string authenticationType)
            : base(authenticationType)
        {
            AuthenticationMode = Security.AuthenticationMode.Active;
            Caption = WsFederationAuthenticationDefaults.Caption;

            _securityTokenHandlers = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers(authenticationType);
            _tokenValidationParameters = new TokenValidationParameters();
            BackchannelTimeout = TimeSpan.FromMinutes(1);    
        }
        public void AddSaml11SecurityTokenHandler(string scheme, SecurityTokenHandlerConfiguration configuration)
        {
            var collection = new SecurityTokenHandlerCollection(configuration)
            {
                new WebSaml11SecurityTokenHandler(),
                new EncryptedSecurityTokenHandler()
            };

            Add(scheme, collection);
        }
Example #27
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);
        }
        public void Add(string scheme, SecurityTokenHandlerCollection collection)
        {
            if (this.ContainsKey(scheme))
            {
                throw new ArgumentException("Scheme already registered.");
            }

            this[scheme] = collection;
            _schemes.Add(scheme);
        }
        public bool TryGetAuthorizationHeaderMapping(string scheme, out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.AuthorizationHeader &&
                       m.Options.Name == "Authorization" &&
                       m.Options.Scheme.Equals(scheme, StringComparison.OrdinalIgnoreCase)
                       select m.TokenHandler).SingleOrDefault();

            return(handler != null);
        }
Example #30
0
        private SecurityToken ReadToken(string text)
        {
            using (XmlReader reader = XmlReader.Create(new StringReader(text)))
            {
                reader.MoveToContent();

                SecurityTokenHandlerCollection handlers = _federationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
                return(handlers.CanReadToken(reader) ? handlers.ReadToken(reader) : null);
            }
        }
Example #31
0
        public WsFederationAuthenticationOptions(string authenticationType)
            : base(authenticationType)
        {
            AuthenticationMode = Security.AuthenticationMode.Active;
            Caption            = WsFederationAuthenticationDefaults.Caption;

            _securityTokenHandlers     = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers(authenticationType);
            _tokenValidationParameters = new TokenValidationParameters();
            BackchannelTimeout         = TimeSpan.FromMinutes(1);
        }
Example #32
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 supported token to an XML string.</summary>
        /// <param name="token">The token.</param>
        /// <param name="handler">The token handler.</param>
        /// <returns>The token XML string.</returns>
        public static string ToTokenXmlString(this SecurityToken token, SecurityTokenHandlerCollection handler)
        {
            if (!handler.CanWriteToken(token))
            {
                throw new InvalidOperationException("Token type not supported");
            }
            var sb = new StringBuilder(128);

            handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);
            return(sb.ToString());
        }
        /// <summary>Turns a supported generic XML security token into a security token.</summary>
        /// <param name="token">The generic XML security token.</param>
        /// <param name="handler">The security token handler.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token,
                                                    SecurityTokenHandlerCollection handler)
        {
            var xmlTextReader = new XmlTextReader(new StringReader(token.TokenXml.OuterXml));

            if (handler.CanReadToken(xmlTextReader))
            {
                return(handler.ReadToken(xmlTextReader));
            }
            throw new InvalidOperationException("Unsupported token type");
        }
        /// <summary>
        /// Initializes an instance of <see cref="WsSecurityTokenSerializerAdapter"/>
        /// </summary>
        /// <param name="securityTokenHandlerCollection">
        /// The <see cref="SecurityTokenHandlerCollection" /> containing the set of <see cref="SecurityTokenHandler" />
        /// objects used for serializing and validating tokens found in WS-Trust messages.
        /// </param>
        /// <param name="securityVersion">The SecurityVersion of the base WSSecurityTokenSerializer.</param>
        /// <param name="trustVersion">The TrustVersion of the serializer uses.</param>
        /// <param name="secureConversationVersion">The SecureConversationVersion of the serializer.</param>
        /// <param name="emitBspAttributes">Flag that determines if the serailization shoudl be BSP compliant.</param>
        /// <param name="samlSerializer">Serializer for SAML 1.1 tokens.</param>
        /// <param name="stateEncoder">SecurityStateEncoder used for resolving SCT.</param>
        /// <param name="knownTypes">The collection of known claim types.</param>
        public WsSecurityTokenSerializerAdapter(SecurityTokenHandlerCollection securityTokenHandlerCollection, SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspAttributes, SamlSerializer samlSerializer, SecurityStateEncoder stateEncoder, IEnumerable <Type> knownTypes)
            : base(securityVersion, trustVersion, secureConversationVersion, emitBspAttributes, samlSerializer, stateEncoder, knownTypes)
        {
            if (securityTokenHandlerCollection == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandlerCollection");
            }

            _scVersion             = secureConversationVersion;
            _securityTokenHandlers = securityTokenHandlerCollection;
        }
Example #36
0
        /// <summary>
        /// Turns a supported generic XML security token to a security token.
        /// </summary>
        /// <param name="token">The generic XML security token.</param>
        /// <param name="handler">The security token handler.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token, SecurityTokenHandlerCollection handler)
        {
            var reader = new XmlTextReader(new StringReader(token.TokenXml.OuterXml));

            if (handler.CanReadToken(reader))
            {
                return handler.ReadToken(reader);
            }
            else
            {
                throw new InvalidOperationException("Unsupported token type");
            }
        }
        public void AddDefaultHandler()
        {
            if (this.ContainsKey("*"))
            {
                throw new ArgumentException("Scheme already registered.");
            }

            var collection = new SecurityTokenHandlerCollection
            {
                new WebDefaultSecurityTokenHandler()
            };

            Add("*", collection);
        }
        /// <summary>
        /// Initializes an instance of <see cref="SecurityTokenSerializerAdapter"/>
        /// </summary>
        /// <param name="securityTokenHandlerCollection">
        /// The <see cref="SecurityTokenHandlerCollection" /> containing the set of <see cref="SecurityTokenHandler" />
        /// </param>
        public SecurityTokenSerializerAdapter(SecurityTokenHandlerCollection securityTokenHandlerCollection)
        {
            if (securityTokenHandlerCollection == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandlerCollection");
            }
            _securityTokenHandlers = securityTokenHandlerCollection;

            KeyInfoSerializer serializer = securityTokenHandlerCollection.KeyInfoSerializer as KeyInfoSerializer;
            if (serializer != null)
            {
                serializer.InnerSecurityTokenSerializer = this;
            }
        }
        /// <summary>
        /// Creates an instance of this object using XML representation of the security token.
        /// </summary>
        /// <param name="securityTokenXml">The <see cref="XmlElement"/> representation of the security token.</param>
        /// <param name="securityTokenHandlers">The collection of <see cref="SecurityTokenHandler"/> objects that may 
        /// be used to read and validate the security token this object represents.</param>
        public SecurityTokenElement(XmlElement securityTokenXml, SecurityTokenHandlerCollection securityTokenHandlers)
        {
            if (securityTokenXml == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenXml");
            }

            if (securityTokenHandlers == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandlers");
            }

            _securityTokenXml = securityTokenXml;
            _securityTokenHandlers = securityTokenHandlers;
        }
        public CustomSecurityTokenServiceConfiguration()
        {
            AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            CertificateValidationMode = X509CertificateValidationMode.None;
            IssuerNameRegistry = new FakeIssuerNameRegistry();
            SecurityTokenService = typeof(CustomSecurityTokenService);
            DefaultTokenLifetime = Configuration.PersistentSessionLength;
            MaximumTokenLifetime = Configuration.PersistentSessionLength;
            TokenIssuerName = Configuration.IssuerName;
            SigningCredentials = new X509SigningCredentials(Configuration.TokenSigningCertificate);

            var actAsHandlers = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] { new Saml11SecurityTokenHandler(), new Saml2SecurityTokenHandler() });
            actAsHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
            actAsHandlers.Configuration.CertificateValidator = X509CertificateValidator.None;
            actAsHandlers.Configuration.IssuerNameRegistry = new FakeIssuerNameRegistry();
            SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.ActAs] = actAsHandlers;
        }
        /// <summary>
        /// Creates an instance of <see cref="SctClaimsHandler"/>
        /// </summary>
        public SctClaimsHandler(
            SecurityTokenHandlerCollection securityTokenHandlerCollection,
            string endpointId)
        {
            if ( securityTokenHandlerCollection == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "securityTokenHandlerCollection" );
            }

            if ( endpointId == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNullOrEmptyString( "endpointId" );
            }

            _securityTokenHandlerCollection = securityTokenHandlerCollection;
            _endpointId = endpointId;
        }
        /// <summary>
        /// Initializes an instance of <see cref="FederatedSecurityTokenManager"/>.
        /// </summary>
        /// <param name="parentCredentials">ServiceCredentials that created this instance of TokenManager.</param>
        /// <exception cref="ArgumentNullException">The argument 'parentCredentials' is null.</exception>
        public FederatedSecurityTokenManager( ServiceCredentials parentCredentials )
            : base( parentCredentials )
        {
            if ( parentCredentials == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials" );
            }

            if ( parentCredentials.IdentityConfiguration == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials.IdentityConfiguration" );
            }

            _exceptionMapper = parentCredentials.ExceptionMapper;

            _securityTokenHandlerCollection = parentCredentials.IdentityConfiguration.SecurityTokenHandlers;                        
            _tokenCache = _securityTokenHandlerCollection.Configuration.Caches.SessionSecurityTokenCache;                        
            _cookieTransforms = SessionSecurityTokenHandler.DefaultCookieTransforms;
        }
    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
        StreamWriter file = new StreamWriter("c:\\temp\\IdentityProviderSts.OnBehalfOfSecurityTokenServiceFactory - CreateServiceHost.txt", true);
        file.WriteLine("_________________________________________");
        file.WriteLine("DateTime: " + DateTime.Now.ToString());

        file.WriteLine("constructorString:" + constructorString);
        file.Close();


        SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("https://ha50idp:8544/IDP-STS/Issue.svc");

        //Uri baseUri = baseAddresses.FirstOrDefault(a => a.Scheme == "https");
        //if (baseUri == null)
        //    throw new InvalidOperationException("The STS should be hosted under https");

        //config.TrustEndpoints.Add(new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetCertificateCredentialsBinding(), baseUri + ""));
        
        // Set the STS implementation class type
        config.SecurityTokenService = typeof(CustomSecurityTokenService);

        // Create a security token handler collection and then provide with a SAML11 security token
        // handler and set the Audience restriction to Never
        SecurityTokenHandlerCollection onBehalfOfHandlers = new SecurityTokenHandlerCollection();
        Saml2SecurityTokenHandler onBehalfOfTokenHandler = new Saml2SecurityTokenHandler();
        
        onBehalfOfHandlers.Add(onBehalfOfTokenHandler);
        //onBehalfOfHandlers.Add(userNameTokenHandler);
        onBehalfOfHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

        // Set the appropriate issuer name registry
        //onBehalfOfHandlers.Configuration.IssuerNameRegistry = new IdentityProviderIssuerNameRegistry();

        // Set the token handlers collection
        config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf] = onBehalfOfHandlers;

//        WindowsUserNameSecurityTokenHandler userNameTokenHandler = new WindowsUserNameSecurityTokenHandler();
//        config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.Default].Add(userNameTokenHandler);
        
        WSTrustServiceHost host = new WSTrustServiceHost(config, baseAddresses);        
        return host;
    }
        private static string SerializeToken(SimpleWebToken accessToken, SecurityTokenHandlerCollection handlers)
        {
            if (handlers.CanWriteToken(accessToken))
            {
                string token = String.Empty;
                using (var sw = new StringWriter())
                {
                    var writer = new XmlTextWriter(sw);
                    handlers.WriteToken(writer, accessToken);

                    // remove the envelope <stringToken>
                    var envelope = sw.ToString();
                    token = XElement.Parse(envelope).Value;
                }

                return token;
            }

            return null;
        }
        public void SecurityTokenHandlerCollectionExtensions_Publics()
        {
            SecurityTokenHandlerCollection securityTokenValidators = new SecurityTokenHandlerCollection();
            string defaultSamlToken = IdentityUtilities.CreateSamlToken();
            string defaultSaml2Token = IdentityUtilities.CreateSaml2Token();
            string defaultJwt = IdentityUtilities.DefaultAsymmetricJwt;

            ExpectedException expectedException = ExpectedException.ArgumentNullException("Parameter name: securityToken");
            ValidateToken(null, null, securityTokenValidators, expectedException);

            expectedException = ExpectedException.ArgumentNullException("Parameter name: validationParameters");
            ValidateToken(defaultSamlToken, null, securityTokenValidators, expectedException);

            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters();
            expectedException = ExpectedException.SecurityTokenValidationException("IDX10201");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            expectedException = ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators.Clear();
            securityTokenValidators.Add(new IMSamlTokenHandler());
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:"));
            ValidateToken(defaultSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.SecurityTokenValidationException(substringExpected: "IDX10201:"));
            securityTokenValidators.Add(new IMSaml2TokenHandler());
            securityTokenValidators.Add(new System.IdentityModel.Tokens.JwtSecurityTokenHandler());
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultJwt, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
        }
        public bool TryGetHeaderMapping(string headerName, out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.Header &&
                             m.Options.Name == headerName
                       select m.TokenHandler).SingleOrDefault();

            return (handler != null);
        }
        public bool TryGetQueryStringMapping(string paramName, out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.QueryString &&
                             m.Options.Name == paramName
                       select m.TokenHandler).SingleOrDefault();

            return (handler != null);
        }
Example #48
0
 /// <summary>
 /// Converts a supported token to an XML string.
 /// </summary>
 /// <param name="token">The token.</param>
 /// <param name="handler">The token handler.</param>
 /// <returns>The token XML string.</returns>
 public static string ToTokenXmlString(this SecurityToken token, SecurityTokenHandlerCollection handler)
 {
     if (handler.CanWriteToken(token))
     {
         var sb = new StringBuilder(128);
         handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);
         return sb.ToString();
     }
     else
     {
         throw new InvalidOperationException("Token type not suppoted");
     }
 }
Example #49
0
        /// <summary>
        /// Converts a SecurityToken to an IClaimsPrincipal.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="handler">The handler.</param>
        /// <returns>An IClaimsPrincipal</returns>
        public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler)
        {
            var ids = handler.ValidateToken(token);

            return new ClaimsPrincipal(from identity in ids select identity);
        }
        public bool TryGetClientCertificateMapping(out SecurityTokenHandlerCollection handler)
        {
            handler = (from m in Mappings
                       where m.Options.RequestType == HttpRequestType.ClientCertificate
                       select m.TokenHandler).SingleOrDefault();

            return (handler != null);
        }
        protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString)
        {
            SecurityTokenHandler handler = null;

            if (handlers.Count == 1)
            {
                handler = handlers.First();
            }
            else
            {
                foreach (var h in handlers)
                {
                    if (h.CanReadToken(tokenString))
                    {
                        handler = h;
                        break;
                    }
                }
            }

            if (handler != null)
            {
                var token = handler.ReadToken(tokenString);
                var principal = new ClaimsPrincipal(handler.ValidateToken(token));

                return principal;
            }

            throw new InvalidOperationException("No handler found");
        }
        public void AddBasicAuthenticationHandler(HttpUserNameSecurityTokenHandler.ValidateUserNameCredentialDelegate validationDelegate)
        {
            var collection = new SecurityTokenHandlerCollection { new HttpUserNameSecurityTokenHandler(validationDelegate) };

            Add("Basic", collection);
        }
 /// <summary>
 ///     Converts a SecurityToken to an IClaimsPrincipal.
 /// </summary>
 /// <param name="token">The token.</param>
 /// <param name="handler">The handler.</param>
 /// <returns>
 ///     An IClaimsPrincipal
 /// </returns>
 public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler)
 {
     return
         new ClaimsPrincipal(handler.ValidateToken(token).Select(identity => identity));
 }
        /// <summary>
        /// Reads a <see cref="SecurityToken"/> from the provided XML representation.
        /// </summary>
        /// <param name="securityTokenXml">The XML representation of the security token.</param>
        /// <param name="securityTokenHandlers">The <see cref="SecurityTokenHandlerCollection"/> used to
        /// read the token.</param>
        /// <returns>A <see cref="SecurityToken"/>.</returns>
        protected virtual SecurityToken ReadSecurityToken(XmlElement securityTokenXml,
                                                           SecurityTokenHandlerCollection securityTokenHandlers)
        {
            SecurityToken securityToken = null;
            XmlReader reader = new XmlNodeReader(securityTokenXml);

            reader.MoveToContent();

            securityToken = securityTokenHandlers.ReadToken(reader);
            if (securityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4051, securityTokenXml, reader.LocalName, reader.NamespaceURI)));
            }

            return securityToken;
        }
        /// <summary>
        /// Creates the identities for the represented by the <see cref="SecurityToken"/>.
        /// </summary>
        /// <param name="securityTokenXml">The <see cref="XmlElement"/> representation of the security token.</param>
        /// <param name="securityTokenHandlers">The collection of <see cref="SecurityTokenHandler"/> objects that may 
        /// be used to read and validate the security token this object represents.</param>
        /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="InvalidOperationException">If either parameter 'securityTokenXml' or 'securityTokenHandlers' are null.</exception>
        protected virtual ReadOnlyCollection<ClaimsIdentity> ValidateToken(XmlElement securityTokenXml, SecurityTokenHandlerCollection securityTokenHandlers)
        {
            if (securityTokenXml == null || securityTokenHandlers == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4052)));
            }

            SecurityToken securityToken = GetSecurityToken();
            return securityTokenHandlers.ValidateToken(securityToken);
        }
        /// <summary>
        /// Loads the <see cref="SecurityTokenHandlerCollectionManager"/> defined for a given service.
        /// </summary>
        /// <param name="serviceElement">The <see cref="IdentityConfigurationElement"/> used to configure this instance.</param>
        /// <returns></returns>
        protected SecurityTokenHandlerCollectionManager LoadHandlers(IdentityConfigurationElement serviceElement)
        {
            //
            // We start with a token handler collection manager that contains a single collection that includes the default
            // handlers for the system.
            //
            SecurityTokenHandlerCollectionManager manager = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            if (serviceElement != null)
            {
                //
                // Load any token handler collections that appear as part of this service element
                //
                if (serviceElement.SecurityTokenHandlerSets.Count > 0)
                {
                    foreach (SecurityTokenHandlerElementCollection handlerElementCollection in serviceElement.SecurityTokenHandlerSets)
                    {
                        try
                        {
                            SecurityTokenHandlerConfiguration handlerConfiguration;
                            SecurityTokenHandlerCollection handlerCollection;

                            if (string.IsNullOrEmpty(handlerElementCollection.Name) ||
                                 StringComparer.Ordinal.Equals(handlerElementCollection.Name, ConfigurationStrings.DefaultConfigurationElementName))
                            {
                                //
                                // For the default collection, merge the IdentityConfiguration with the underlying config, if it exists.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    //
                                    // Configuration from a nested configuration object. We start with Service level configuration for 
                                    // handlers and then override the collection specific configuration. The result is a new configuration
                                    // object that can only be modified by accessing the collection or handlers configuration properties.
                                    //
                                    _serviceHandlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                    handlerConfiguration = LoadHandlerConfiguration(_serviceHandlerConfiguration, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // No nested configuration object. We use the values from the ServiceElement for this case.
                                    //
                                    handlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                }

                                _serviceHandlerConfiguration = handlerConfiguration;
                            }
                            else
                            {
                                //
                                // This is a non-default collection. There should be no settings inherited from IdentityConfiguration.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    handlerConfiguration = LoadHandlerConfiguration(null, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // If there is no underlying config, set everything as default.
                                    //
                                    handlerConfiguration = new SecurityTokenHandlerConfiguration();
                                }
                            }

                            handlerCollection = new SecurityTokenHandlerCollection(handlerConfiguration);
                            manager[handlerElementCollection.Name] = handlerCollection;

                            foreach (CustomTypeElement handlerElement in handlerElementCollection)
                            {
                                handlerCollection.Add(CustomTypeElement.Resolve<SecurityTokenHandler>(handlerElement));
                            }
                        }
                        catch (ArgumentException inner)
                        {
                            throw DiagnosticUtility.ThrowHelperConfigurationError(serviceElement, handlerElementCollection.Name, inner);
                        }
                    }
                }
                //
                // Ensure that the default usage collection always exists
                //
                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }
            else
            {
                //
                // Ensure that the default usage collection always exists
                //
                _serviceHandlerConfiguration = new SecurityTokenHandlerConfiguration();

                _serviceHandlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;

                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }

            return manager;
        }
        public void AddBasicAuthenticationHandler(SecurityTokenHandler handler)
        {
            var collection = new SecurityTokenHandlerCollection { handler };

            Add("Basic", collection);
        }
        protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString)
        {
            SecurityTokenHandler handler = null;

            if (handlers.Count == 1)
            {
                handler = handlers.First();
            }
            else
            {
                foreach (var h in handlers)
                {
                    if (h.CanReadToken(tokenString))
                    {
                        handler = h;
                        break;
                    }
                }
            }

            if (handler != null)
            {
                Tracing.Information(Area.HttpAuthentication, "Invoking token handler: " + handler.GetType().FullName);

                var token = handler.ReadToken(tokenString);
                var principal = new ClaimsPrincipal(handler.ValidateToken(token));

                return principal;
            }

            throw new InvalidOperationException("No handler found");
        }
        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);
        }
 public AdfsBridge(IConfigurationRepository configuration)
 {
     _configuration = configuration;
     _handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
 }