Exemplo n.º 1
0
        private ClaimsPrincipal ParseToken(GenericXmlSecurityToken genericToken)
        {
            using (XmlReader samlReader = XmlReader.Create(new StringReader(genericToken.TokenXml.OuterXml)))
            {
                SecurityTokenHandlerCollection tokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();

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

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

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

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

                ClaimsIdentity tokenIdentity = tokenHandlers.ValidateToken(samlToken).FirstOrDefault();
                return(new ClaimsPrincipal(tokenIdentity));
            }
        }
        public 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));
        }
Exemplo n.º 3
0
        /// <summary>
        /// The out-of-band token resolver to be used if the authenticator does
        /// not provide another.
        /// </summary>
        /// <remarks>By default this will create the resolver with the service certificate and
        /// know certificates collections specified in the service credentials when the STS is
        /// hosted inside WCF.</remarks>
        SecurityTokenResolver GetDefaultOutOfBandTokenResolver()
        {
            if (_defaultTokenResolver == null)
            {
                lock ( _syncObject )
                {
                    if (_defaultTokenResolver == null)
                    {
                        //
                        // Create default Out-Of-Band SecurityResolver.
                        //
                        List <SecurityToken> outOfBandTokens = new List <SecurityToken>();
                        if (base.ServiceCredentials.ServiceCertificate.Certificate != null)
                        {
                            outOfBandTokens.Add(new X509SecurityToken(base.ServiceCredentials.ServiceCertificate.Certificate));
                        }

                        if ((base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates != null) && (base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count > 0))
                        {
                            for (int i = 0; i < base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count; ++i)
                            {
                                outOfBandTokens.Add(new X509SecurityToken(base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates[i]));
                            }
                        }

                        _defaultTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(outOfBandTokens.AsReadOnly(), false);
                    }
                }
            }

            return(_defaultTokenResolver);
        }
Exemplo n.º 4
0
        private JsonWebSecurityTokenHandler GetSecurityTokenHandler(string audience,
                                                                    string authMetadataEndpoint,
                                                                    X509Certificate2 currentCertificate)
        {
            JsonWebSecurityTokenHandler jsonTokenHandler = new JsonWebSecurityTokenHandler();

            jsonTokenHandler.Configuration = new Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration();

            jsonTokenHandler.Configuration.AudienceRestriction = new Microsoft.IdentityModel.Tokens.AudienceRestriction(AudienceUriMode.Always);
            jsonTokenHandler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(
                new Uri(audience, UriKind.RelativeOrAbsolute));

            jsonTokenHandler.Configuration.CertificateValidator = X509CertificateValidator.None;

            jsonTokenHandler.Configuration.IssuerTokenResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                    new ReadOnlyCollection <SecurityToken>(new List <SecurityToken>(
                                                               new SecurityToken[]
            {
                new X509SecurityToken(currentCertificate)
            })), false);

            Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry issuerNameRegistry =
                new Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry();
            issuerNameRegistry.AddTrustedIssuer(currentCertificate.Thumbprint, Config.ExchangeApplicationIdentifier);
            jsonTokenHandler.Configuration.IssuerNameRegistry = issuerNameRegistry;

            return(jsonTokenHandler);
        }
        private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler(string clientSecret)
        {
            JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();

            handler.Configuration = new Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration();
            handler.Configuration.AudienceRestriction  = new Microsoft.IdentityModel.Tokens.AudienceRestriction(AudienceUriMode.Never);
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;

            List <byte[]> securityKeys = new List <byte[]>();

            securityKeys.Add(Convert.FromBase64String(clientSecret));

            List <SecurityToken> securityTokens = new List <SecurityToken>();

            securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));

            handler.Configuration.IssuerTokenResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                    new ReadOnlyCollection <SecurityToken>(securityTokens),
                    false);
            SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();

            foreach (byte[] securitykey in securityKeys)
            {
                issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(""));
            }
            handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
            return(handler);
        }
 private static SecurityTokenResolver CreateSecurityTokenResolver(this X509Certificate2 certificate)
 {
     return(SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new List <SecurityToken>
     {
         new X509SecurityToken(certificate)
     }.AsReadOnly(), true));
 }
        /// <summary>
        /// Initializes the validator from the configuration for a token policy.
        /// </summary>
        /// <param name="issuerCertificate">The issuer certificate.</param>
        private SecurityTokenResolver CreateSecurityTokenResolver(CertificateIdentifier issuerCertificate)
        {
            if (issuerCertificate == null)
            {
                throw new ArgumentNullException("issuerCertificate");
            }

            // find the certificate.
            X509Certificate2 certificate = issuerCertificate.Find(false);

            if (certificate == null)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadCertificateInvalid,
                          "Could not find issuer certificate: {0}",
                          issuerCertificate);
            }

            // create a security token representing the certificate.
            List <SecurityToken> tokens = new List <SecurityToken>();

            tokens.Add(new X509SecurityToken(certificate));

            // create issued token resolver.
            SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new System.Collections.ObjectModel.ReadOnlyCollection <SecurityToken>(tokens),
                false);

            return(tokenResolver);
        }
    public static void Methods_NonNullParam_InvokeAndReturn()
    {
        var xmlReader           = XmlReader.Create(new MemoryStream());
        var xmlWriter           = XmlWriter.Create(new MemoryStream());
        var dummyToken          = new DummySecurityToken();
        var keyIdentifier       = new SecurityKeyIdentifier();
        var keyIdentifierClause = new SecurityKeyIdentifierClauseImpl("DummyClause");
        var sts = new SecurityTokenSerializerImpl();

        Assert.NotNull(sts);
        Assert.True(sts.CanReadKeyIdentifier(xmlReader));
        Assert.True(sts.CanReadKeyIdentifierClause(xmlReader));
        Assert.True(sts.CanReadToken(xmlReader));
        Assert.True(sts.CanWriteKeyIdentifier(keyIdentifier));
        Assert.True(sts.CanWriteKeyIdentifierClause(keyIdentifierClause));
        Assert.True(sts.CanWriteToken(dummyToken));

        SecurityToken token = sts.ReadToken(xmlReader, SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(new List <SecurityToken>()
        {
            dummyToken
        }), false));
        SecurityKeyIdentifier       identifier       = sts.ReadKeyIdentifier(xmlReader);
        SecurityKeyIdentifierClause identifierClause = sts.ReadKeyIdentifierClause(xmlReader);

        Assert.IsType <DummySecurityToken>(token);
        Assert.IsType <SecurityKeyIdentifier>(identifier);
        Assert.IsType <SecurityKeyIdentifierClauseImpl>(identifierClause);

        sts.WriteToken(xmlWriter, dummyToken);
        sts.WriteKeyIdentifier(xmlWriter, keyIdentifier);
        sts.WriteKeyIdentifierClause(xmlWriter, keyIdentifierClause);
        Assert.True(sts.WriteTokenCoreCalled);
        Assert.True(sts.WriteKeyIdentifierCoreCalled);
        Assert.True(sts.WriteKeyIdentifierClauseCoreCalled);
    }
Exemplo n.º 9
0
        private JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
        {
            JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();

            handler.Configuration = new SecurityTokenHandlerConfiguration();
            handler.Configuration.AudienceRestriction  = new AudienceRestriction(AudienceUriMode.Never);
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;

            List <byte[]> securityKeys = new List <byte[]>();

            securityKeys.Add(Convert.FromBase64String(_clientSecret));
            if (!string.IsNullOrEmpty(_secondaryClientSecret))
            {
                securityKeys.Add(Convert.FromBase64String(_secondaryClientSecret));
            }

            List <SecurityToken> securityTokens = new List <SecurityToken>();

            securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));

            handler.Configuration.IssuerTokenResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                    new ReadOnlyCollection <SecurityToken>(securityTokens),
                    false);
            SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();

            foreach (byte[] securitykey in securityKeys)
            {
                issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(_serviceNamespace));
            }
            handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
            return(handler);
        }
        /// <summary>
        /// Creates a <see cref="WSTrustSerializationContext" /> used by <see cref="WSTrustChannel" /> objects created
        /// by this factory.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If <see cref="WSTrustChannelFactory.SecurityTokenResolver" /> is set to null, the
        /// ClientCertificate set on the factory's  Endpoint's ClientCredentials behavior will be used to
        /// create a resolver. If no such certificate is found, an empty resolver is used.
        /// </para>
        /// <para>
        /// If <see cref="WSTrustChannelFactory.UseKeyTokenResolver" /> is set to null, an empty resolver
        /// will be used.
        /// </para>
        /// </remarks>
        /// <returns>A WSTrustSerializationContext initialized with the trust client's properties.</returns>
        protected virtual WSTrustSerializationContext CreateSerializationContext()
        {
            //
            // Create a resolver with the ClientCredential's ClientCertificate if a resolver is not set.
            //
            SecurityTokenResolver resolver = _securityTokenResolver;

            if (resolver == null)
            {
                ClientCredentials factoryCredentials = Credentials;
                if (null != factoryCredentials.ClientCertificate && null != factoryCredentials.ClientCertificate.Certificate)
                {
                    List <SecurityToken> clientCredentialTokens = new List <SecurityToken>();
                    clientCredentialTokens.Add(new X509SecurityToken(factoryCredentials.ClientCertificate.Certificate));
                    resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(clientCredentialTokens.AsReadOnly(), false);
                }
            }

            //
            // If it is _still_ null, then make it empty.
            //
            if (resolver == null)
            {
                resolver = EmptySecurityTokenResolver.Instance;
            }

            //
            // UseKeyTokenResolver is empty if null.
            //
            SecurityTokenResolver useKeyResolver = _useKeyTokenResolver ?? EmptySecurityTokenResolver.Instance;

            return(new WSTrustSerializationContext(_securityTokenHandlerCollectionManager, resolver, useKeyResolver));
        }
Exemplo n.º 11
0
        static void TransportTransportMessageReceived(object sender, TransportMessageReceivedEventArgs e)
        {
            if (!ConfigureClaimFlow.Flow)
            {
                return;
            }
            if (!e.Message.Headers.ContainsKey(SecurityTokenKey))
            {
                return;
            }

            var serializedToken = e.Message.Headers[SecurityTokenKey];
            var certificate     = ExtractCertificate(serializedToken);
            var handler         = new Saml2SecurityTokenHandler(new SamlSecurityTokenRequirement());
            var tokens          = new List <SecurityToken> {
                new X509SecurityToken(certificate)
            };
            var resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);

            handler.Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerTokenResolver  = resolver,
                IssuerNameRegistry   = new InternalIssuerNameRegistry(),
                CertificateValidator = X509CertificateValidator.None
            };
            using (var reader = XmlReader.Create(new StringReader(serializedToken)))
            {
                var bootstrapToken = handler.ReadToken(reader);
                handler.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
                handler.Configuration.MaxClockSkew = TimeSpan.MaxValue;
                var collection = handler.ValidateToken(bootstrapToken);
                Thread.CurrentPrincipal = new ClaimsPrincipal(collection);
            }
        }
        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));
        }
        protected override void ValidateTestCase(string testCase)
        {
            IdentityConfiguration identityConfig = new IdentityConfiguration(IdentityConfiguration.DefaultServiceName);

            JwtSecurityTokenHandler jwtHandler = identityConfig.SecurityTokenHandlers[typeof(JwtSecurityToken)] as JwtSecurityTokenHandler;

            jwtHandler.RequireExpirationTime = false;
            Assert.IsNotNull(jwtHandler);

            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor()
            {
                TokenIssuerName    = "https://wiftooling.accesscontrol.windows.net",
                AppliesToAddress   = "http://localhost",
                SigningCredentials = KeyingMaterial.X509SigningCreds_2048_RsaSha2_Sha2,
            };

            try
            {
                SecurityToken        jwtToken    = jwtHandler.CreateToken(tokenDescriptor);
                string               tokenString = jwtHandler.WriteToken(jwtToken);
                List <SecurityToken> tokens      = new List <SecurityToken>(KeyingMaterial.AsymmetricTokens);
                jwtHandler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), true);
                jwtToken = jwtHandler.ReadToken(tokenString);
                jwtHandler.CertificateValidator             = X509CertificateValidator.None;
                jwtHandler.Configuration.IssuerNameRegistry = new  SetNameIssuerNameRegistry("https://wiftooling.accesscontrol.windows.net");
                ClaimsPrincipal cp = new ClaimsPrincipal(jwtHandler.ValidateToken(jwtToken));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Decrpyts a security token from an XML EncryptedData
        /// </summary>
        /// <param name="reader">The encrypted token XML reader.</param>
        /// <returns>A byte array of the contents of the encrypted token</returns>
        internal byte[] DecryptToken(XmlReader reader)
        {
            Requires.NotNull(reader, "reader");
            Contract.Ensures(Contract.Result <byte[]>() != null);

            byte[] securityTokenData;
            string encryptionAlgorithm;
            SecurityKeyIdentifier keyIdentifier;
            bool isEmptyElement;

            ErrorUtilities.VerifyInternal(reader.IsStartElement(XmlEncryptionStrings.EncryptedData, XmlEncryptionStrings.Namespace), "Expected encrypted token starting XML element was not found.");
            reader.Read();             // get started

            // if it's not an encryption method, something is dreadfully wrong.
            InfoCardErrorUtilities.VerifyInfoCard(reader.IsStartElement(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace), InfoCardStrings.EncryptionAlgorithmNotFound);

            // Looks good, let's grab the alg.
            isEmptyElement      = reader.IsEmptyElement;
            encryptionAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm);
            reader.Read();

            if (!isEmptyElement)
            {
                while (reader.IsStartElement())
                {
                    reader.Skip();
                }
                reader.ReadEndElement();
            }

            // get the key identifier
            keyIdentifier = WSSecurityTokenSerializer.DefaultInstance.ReadKeyIdentifier(reader);

            // resolve the symmetric key
            SymmetricSecurityKey decryptingKey = (SymmetricSecurityKey)SecurityTokenResolver.CreateDefaultSecurityTokenResolver(this.tokens.AsReadOnly(), false).ResolveSecurityKey(keyIdentifier[0]);
            SymmetricAlgorithm   algorithm     = decryptingKey.GetSymmetricAlgorithm(encryptionAlgorithm);

            // dig for the security token data itself.
            reader.ReadStartElement(XmlEncryptionStrings.CipherData, XmlEncryptionStrings.Namespace);
            reader.ReadStartElement(XmlEncryptionStrings.CipherValue, XmlEncryptionStrings.Namespace);
            securityTokenData = Convert.FromBase64String(reader.ReadString());
            reader.ReadEndElement();             // CipherValue
            reader.ReadEndElement();             // CipherData
            reader.ReadEndElement();             // EncryptedData

            // decrypto-magic!
            int blockSizeBytes = algorithm.BlockSize / 8;

            byte[] iv = new byte[blockSizeBytes];
            Buffer.BlockCopy(securityTokenData, 0, iv, 0, iv.Length);
            algorithm.Padding = PaddingMode.ISO10126;
            algorithm.Mode    = CipherMode.CBC;
            ICryptoTransform decrTransform = algorithm.CreateDecryptor(algorithm.Key, iv);

            byte[] plainText = decrTransform.TransformFinalBlock(securityTokenData, iv.Length, securityTokenData.Length - iv.Length);
            decrTransform.Dispose();

            return(plainText);
        }
Exemplo n.º 15
0
        private void ParseToken(string xmlToken, X509Certificate2 cert)
        {
            int    skew      = 300; // default to 5 minutes
            string tokenskew = System.Configuration.ConfigurationManager.AppSettings["MaximumClockSkew"];

            if (!string.IsNullOrEmpty(tokenskew))
            {
                skew = Int32.Parse(tokenskew);
            }

            XmlReader     tokenReader = new XmlTextReader(new StringReader(xmlToken));
            EncryptedData enc         = new EncryptedData();

            enc.TokenSerializer = WSSecurityTokenSerializer.DefaultInstance;

            enc.ReadFrom(tokenReader);

            List <SecurityToken> tokens          = new List <SecurityToken>();
            SecurityToken        encryptingToken = new X509SecurityToken(cert);

            tokens.Add(encryptingToken);

            SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
            SymmetricSecurityKey  encryptingCrypto;

            // an error here usually means that you have selected the wrong key.
            encryptingCrypto = (SymmetricSecurityKey)tokenResolver.ResolveSecurityKey(enc.KeyIdentifier[0]);

            SymmetricAlgorithm algorithm = encryptingCrypto.GetSymmetricAlgorithm(enc.EncryptionMethod);

            byte[] decryptedData = enc.GetDecryptedBuffer(algorithm);

            SecurityTokenSerializer tokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8));

            m_token = (SamlSecurityToken)tokenSerializer.ReadToken(reader, tokenResolver);


            SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List <SecurityTokenAuthenticator>(
                                                                                                  new SecurityTokenAuthenticator[] {
                new RsaSecurityTokenAuthenticator(),
                new X509SecurityTokenAuthenticator()
            }), new TimeSpan(0, 0, skew));


            if (authenticator.CanValidateToken(m_token))
            {
                ReadOnlyCollection <IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token);
                m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies);
                m_identityClaims       = FindIdentityClaims(m_authorizationContext);
            }
            else
            {
                throw new Exception("Unable to validate the token.");
            }
        }
Exemplo n.º 16
0
        private SamlSecurityTokenAuthenticator CreateSamlTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            SamlSecurityTokenAuthenticator authenticator;

            if (recipientRequirement == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("recipientRequirement");
            }
            Collection <SecurityToken> collection = new Collection <SecurityToken>();

            if (this.parent.ServiceCertificate.Certificate != null)
            {
                collection.Add(new X509SecurityToken(this.parent.ServiceCertificate.Certificate));
            }
            List <SecurityTokenAuthenticator> supportingAuthenticators = new List <SecurityTokenAuthenticator>();

            if ((this.parent.IssuedTokenAuthentication.KnownCertificates != null) && (this.parent.IssuedTokenAuthentication.KnownCertificates.Count > 0))
            {
                for (int i = 0; i < this.parent.IssuedTokenAuthentication.KnownCertificates.Count; i++)
                {
                    collection.Add(new X509SecurityToken(this.parent.IssuedTokenAuthentication.KnownCertificates[i]));
                }
            }
            X509CertificateValidator certificateValidator = this.parent.IssuedTokenAuthentication.GetCertificateValidator();

            supportingAuthenticators.Add(new X509SecurityTokenAuthenticator(certificateValidator));
            if (this.parent.IssuedTokenAuthentication.AllowUntrustedRsaIssuers)
            {
                supportingAuthenticators.Add(new RsaSecurityTokenAuthenticator());
            }
            outOfBandTokenResolver = (collection.Count > 0) ? SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(collection), false) : null;
            if ((recipientRequirement.SecurityBindingElement == null) || (recipientRequirement.SecurityBindingElement.LocalServiceSettings == null))
            {
                authenticator = new SamlSecurityTokenAuthenticator(supportingAuthenticators);
            }
            else
            {
                authenticator = new SamlSecurityTokenAuthenticator(supportingAuthenticators, recipientRequirement.SecurityBindingElement.LocalServiceSettings.MaxClockSkew);
            }
            authenticator.AudienceUriMode = this.parent.IssuedTokenAuthentication.AudienceUriMode;
            IList <string> allowedAudienceUris = authenticator.AllowedAudienceUris;

            if (this.parent.IssuedTokenAuthentication.AllowedAudienceUris != null)
            {
                for (int j = 0; j < this.parent.IssuedTokenAuthentication.AllowedAudienceUris.Count; j++)
                {
                    allowedAudienceUris.Add(this.parent.IssuedTokenAuthentication.AllowedAudienceUris[j]);
                }
            }
            if (recipientRequirement.ListenUri != null)
            {
                allowedAudienceUris.Add(recipientRequirement.ListenUri.AbsoluteUri);
            }
            return(authenticator);
        }
Exemplo n.º 17
0
        private static SecurityTokenHandlerConfiguration CreateSaml2SecurityTokenHandlerConfiguration(string issuerThumbprint, string issuerName, string audienceUri, X509CertificateValidator certificateValidator, X509Certificate2 encryptingCertificate)
        {
            var handlerConfig = CreateSaml2SecurityTokenHandlerConfiguration(issuerThumbprint, issuerName, audienceUri, certificateValidator);

            var serviceTokens = new List<SecurityToken> { new X509SecurityToken(encryptingCertificate) };

            handlerConfig.ServiceTokenResolver =
               SecurityTokenResolver.CreateDefaultSecurityTokenResolver(serviceTokens.AsReadOnly(), true);

            return handlerConfig;
        }
Exemplo n.º 18
0
        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;
        }
Exemplo n.º 19
0
        private static void ConfigureHandler(SecurityTokenHandlerConfiguration hc, IFederatedAuthenticationSettings settings)
        {
            hc.AudienceRestriction  = new AudienceRestriction(AudienceUriMode.Never);
            hc.CertificateValidator = new SamlCertificateValidator(settings.Certificate, WebApiConfig.VerifyCertificateChain);
            hc.IssuerNameRegistry   = new SamlIssuerNameRegistry(settings.Certificate);
            hc.IssuerTokenResolver  = new IssuerTokenResolver();

            // need this if certificate not included into sign info
            var tokens = new List <SecurityToken> {
                new X509SecurityToken(settings.Certificate)
            };

            hc.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new ReadOnlyCollection <SecurityToken>(tokens), false);
        }
Exemplo n.º 20
0
        void ReadHeaders(Message srcmsg)
        {
            SecurityTokenSerializer serializer =
                security.TokenSerializer;

            tokens         = new List <SecurityToken> ();
            token_resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new ReadOnlyCollection <SecurityToken> (tokens),
                true);
            token_resolver = new UnionSecurityTokenResolver(token_resolver, security.OutOfBandTokenResolver);

            // Add relevant protection token and supporting tokens.
            tokens.Add(security.EncryptionToken);
            // FIXME: this is just a workaround for symmetric binding to not require extra client certificate.
            if (security.Element is AsymmetricSecurityBindingElement)
            {
                tokens.Add(security.SigningToken);
            }
            if (RequestSecurity != null && RequestSecurity.ProtectionToken != null)
            {
                tokens.Add(RequestSecurity.ProtectionToken.SecurityToken);
            }
            // FIXME: handle supporting tokens

            for (int i = 0; i < srcmsg.Headers.Count; i++)
            {
                MessageHeaderInfo header = srcmsg.Headers [i];
                // FIXME: check SOAP Actor.
                // MessageHeaderDescription.Actor needs to be accessible from here.
                if (header.Namespace == Constants.WssNamespace &&
                    header.Name == "Security")
                {
                    wss_header        = new WSSecurityMessageHeader(null);
                    wss_header_reader = new WSSecurityMessageHeaderReader(wss_header, serializer, token_resolver, doc, nsmgr, tokens);
                    wss_header_reader.ReadContents(srcmsg.Headers.GetReaderAtHeader(i));
                    headers.Add(wss_header);
                }
                else
                {
                    headers.Add(header);
                }
            }
            if (wss_header == null)
            {
                throw new InvalidOperationException("In this service contract, a WS-Security header is required in the Message, but was not found.");
            }
        }
Exemplo n.º 21
0
    public CardSignIn()
    {
        SecurityTokenHandlerConfiguration handlerConfig = new SecurityTokenHandlerConfiguration();

        handlerConfig.IssuerNameRegistry = new TrustedIssuerNameRegistry();

        List <SecurityToken> servicetokens = new List <SecurityToken>(1);

        servicetokens.Add(new X509SecurityToken(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=localhost")));
        handlerConfig.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(servicetokens.AsReadOnly(), false);

        handlerConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://localhost/AuthAssuranceSTS/CardSignIn.aspx"));

        _handlers = new SecurityTokenHandlerCollection(handlerConfig);

        SamlSecurityTokenRequirement samlReqs = new SamlSecurityTokenRequirement();

        _handlers.Add(new EncryptedSecurityTokenHandler());
        _handlers.Add(new Saml11SecurityTokenHandler(samlReqs));
    }
Exemplo n.º 22
0
        public void AsymmetricSignatureProvider_Extensibility()
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            Console.WriteLine("Testvariation: " + "outbound signature algorithm - bobsYourUncle");

            // inbound signature algorithm - bobsYourUncle
            JwtSecurityTokenHandler.OutboundAlgorithmMap.Remove(SecurityAlgorithms.RsaSha256Signature);
            JwtSecurityTokenHandler.OutboundAlgorithmMap.Add(new KeyValuePair <string, string>(SecurityAlgorithms.RsaSha256Signature, "bobsYourUncle"));
            JwtSecurityToken     jwt    = handler.CreateToken(issuer: Issuers.GotJwt, signingCredentials: KeyingMaterial.X509SigningCreds_2048_RsaSha2_Sha2) as JwtSecurityToken;
            List <SecurityToken> tokens = new List <SecurityToken>()
            {
                KeyingMaterial.X509Token_2048
            };

            handler.Configuration = new SecurityTokenHandlerConfiguration()
            {
                IssuerTokenResolver  = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), true),
                SaveBootstrapContext = true,
                CertificateValidator = AlwaysSucceedCertificateValidator.New,
                AudienceRestriction  = new AudienceRestriction(AudienceUriMode.Never),
            };

            // inbound unknown algorithm
            ExpectedException expectedException = ExpectedException.SecVal(id: "Jwt10316");

            try
            {
                handler.ValidateToken(jwt);
                ExpectedException.ProcessNoException(expectedException);
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(expectedException, ex);
            }
            finally
            {
                JwtSecurityTokenHandler.OutboundAlgorithmMap.Remove(SecurityAlgorithms.RsaSha256Signature);
                JwtSecurityTokenHandler.OutboundAlgorithmMap.Add(new KeyValuePair <string, string>(SecurityAlgorithms.RsaSha256Signature, "RS256"));
            }
        }
Exemplo n.º 23
0
        public ActionResult ProcessWSFedResponse()
        {
            var fam = new WSFederationAuthenticationModule();

            fam.FederationConfiguration = new FederationConfiguration();

            if (ConfigurationRepository.Keys.DecryptionCertificate != null)
            {
                var idConfig = new IdentityConfiguration();

                idConfig.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                    new ReadOnlyCollection <SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false);
                fam.FederationConfiguration.IdentityConfiguration = idConfig;
            }

            if (fam.CanReadSignInResponse(Request))
            {
                var token = fam.GetSecurityToken(Request);
                return(ProcessWSFedSignInResponse(fam.GetSignInResponseMessage(Request), token));
            }

            return(View("Error"));
        }
Exemplo n.º 24
0
        private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
        {
            JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();

            handler.Configuration = new Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration();
            handler.Configuration.AudienceRestriction  = new Microsoft.IdentityModel.Tokens.AudienceRestriction(AudienceUriMode.Never);
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;

            byte[] key = Convert.FromBase64String(ClientSecret);
            handler.Configuration.IssuerTokenResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                    new ReadOnlyCollection <SecurityToken>(new List <SecurityToken>(
                                                               new SecurityToken[]
            {
                new SimpleSymmetricKeySecurityToken(key)
            })),
                    false);
            SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();

            issuerNameRegistry.AddTrustedIssuer(key, GetAcsPrincipalName(ServiceNamespace));
            handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
            return(handler);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Decrpyts a security token from an XML EncryptedData
        /// </summary>
        /// <param name="xmlToken">the XML token to decrypt</param>
        /// <returns>A byte array of the contents of the encrypted token</returns>
        public static byte[] DecryptToken(string xmlToken)
        {
            XmlReader reader = new XmlTextReader(new StringReader(xmlToken));

            byte[] securityTokenData;
            string encryptionAlgorithm;
            SecurityKeyIdentifier keyIdentifier;
            bool isEmptyElement;

            // if it's not an xml:enc element, something is dreadfully wrong.
            if (!reader.IsStartElement(XmlEncryptionStrings.EncryptedData, XmlEncryptionStrings.Namespace))
            {
                throw new InvalidOperationException();
            }

            reader.Read(); // looks good.

            // if it's not an encryption method, something is dreadfully wrong.
            if (!reader.IsStartElement(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace))
            {
                throw new InformationCardException("Failed to find the encryptionAlgorithm");
            }

            // Looks good, let's grab the alg.
            isEmptyElement      = reader.IsEmptyElement;
            encryptionAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm);
            reader.Read();

            if (!isEmptyElement)
            {
                while (reader.IsStartElement())
                {
                    reader.Skip();
                }
                reader.ReadEndElement();
            }

            // get the key identifier
            keyIdentifier = WSSecurityTokenSerializer.DefaultInstance.ReadKeyIdentifier(reader);

            // resolve the symmetric key
            SymmetricSecurityKey decryptingKey = (SymmetricSecurityKey)SecurityTokenResolver.CreateDefaultSecurityTokenResolver(Tokens.AsReadOnly(), false).ResolveSecurityKey(keyIdentifier[0]);
            SymmetricAlgorithm   algorithm     = decryptingKey.GetSymmetricAlgorithm(encryptionAlgorithm);

            // dig for the security token data itself.
            reader.ReadStartElement(XmlEncryptionStrings.CipherData, XmlEncryptionStrings.Namespace);
            reader.ReadStartElement(XmlEncryptionStrings.CipherValue, XmlEncryptionStrings.Namespace);
            securityTokenData = Convert.FromBase64String(reader.ReadString());
            reader.ReadEndElement(); // CipherValue
            reader.ReadEndElement(); // CipherData
            reader.ReadEndElement(); // EncryptedData

            // decrypto-magic!
            int ivSize = algorithm.BlockSize / 8;

            byte[] iv = new byte[ivSize];
            Buffer.BlockCopy(securityTokenData, 0, iv, 0, iv.Length);
            algorithm.Padding = PaddingMode.ISO10126;
            algorithm.Mode    = CipherMode.CBC;
            ICryptoTransform decrTransform = algorithm.CreateDecryptor(algorithm.Key, iv);

            byte[] plainText = decrTransform.TransformFinalBlock(securityTokenData, iv.Length, securityTokenData.Length - iv.Length);
            decrTransform.Dispose();

            return(plainText);
        }
        public override NameValueCollection Validate(TokenRequestMessage message)
        {
            if (!this.CanValidateMessage(message))
            {
                throw new OAuthException(OAuthErrorCodes.UnsupportedGrantType, "This handler cannot validate this message.");
            }

            if (!message.Parameters[OAuthConstants.AssertionType].Equals("saml", StringComparison.OrdinalIgnoreCase))
            {
                throw new OAuthException(OAuthErrorCodes.InvalidRequest, string.Format("Assertion format '{0}' not supported. Only Saml Supported", message.Parameters[OAuthConstants.AssertionType]));
            }

            string assertion = message.Parameters[OAuthConstants.Assertion];

            if (assertion == null)
            {
                throw new OAuthException(OAuthErrorCodes.InvalidRequest, "Parameter 'assertion' is mandatory");
            }

            this.EnsureClientExists(message);

            SecurityToken token  = null;
            SecurityToken xtoken = null;

            using (var stringReader = new StringReader(assertion))
            {
                var reader = XmlReader.Create(stringReader);
                if (!ServiceConfiguration.SecurityTokenHandlers.CanReadToken(reader))
                {
                    throw new OAuthException(OAuthErrorCodes.UnsupportedGrantType, "No Token handler defined can read this assertion");
                }

                // TODO: this should be changed to be in config
                // CHANGE: matias: read decryption cert from servicecertificate instead of hardcoding localhost
                using (var xprovider = new X509SecurityTokenProvider(ServiceConfiguration.ServiceCertificate))
                {
                    xtoken = xprovider.GetToken(new TimeSpan(10, 1, 1));
                }

                var outOfBandTokens = new Collection <SecurityToken>();
                outOfBandTokens.Add(xtoken);

                // CHANGED: matias, don't validate certificate (should be read from service config)
                ServiceConfiguration.CertificateValidator = X509CertificateValidator.None;

                // encryptedtoken handler is 6 . Add the X509TOken which has the key to decrypt this token
                ServiceConfiguration.SecurityTokenHandlers[6].Configuration.ServiceTokenResolver =
                    SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(outOfBandTokens), false);

                token = ServiceConfiguration.SecurityTokenHandlers.ReadToken(reader);
            }

            ClaimsIdentityCollection cc;

            try
            {
                cc = ServiceConfiguration.SecurityTokenHandlers.ValidateToken(token);
            }
            catch (SecurityTokenException ex)
            {
                throw new OAuthException(OAuthErrorCodes.InvalidGrant, ex.Message, ex);
            }

            // CHANGE: matias: add CAM in order to be able to tranform claims
            IClaimsPrincipal principal = new ClaimsPrincipal(cc);

            if (ServiceConfiguration.ClaimsAuthenticationManager != null)
            {
                principal = ServiceConfiguration.ClaimsAuthenticationManager.Authenticate("replace", principal);
            }

            var collection = new NameValueCollection();

            foreach (Claim claim in cc[0].Claims)
            {
                collection.Add(claim.ClaimType, claim.Value);
            }

            return(collection);
        }
        SamlSecurityTokenAuthenticator CreateSamlTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            if (recipientRequirement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("recipientRequirement");
            }

            Collection <SecurityToken> outOfBandTokens = new Collection <SecurityToken>();

            if (parent.ServiceCertificate.Certificate != null)
            {
                outOfBandTokens.Add(new X509SecurityToken(parent.ServiceCertificate.Certificate));
            }
            List <SecurityTokenAuthenticator> supportingAuthenticators = new List <SecurityTokenAuthenticator>();

            if ((parent.IssuedTokenAuthentication.KnownCertificates != null) && (parent.IssuedTokenAuthentication.KnownCertificates.Count > 0))
            {
                for (int i = 0; i < parent.IssuedTokenAuthentication.KnownCertificates.Count; ++i)
                {
                    outOfBandTokens.Add(new X509SecurityToken(parent.IssuedTokenAuthentication.KnownCertificates[i]));
                }
            }

            X509CertificateValidator validator = parent.IssuedTokenAuthentication.GetCertificateValidator();

            supportingAuthenticators.Add(new X509SecurityTokenAuthenticator(validator));

            if (parent.IssuedTokenAuthentication.AllowUntrustedRsaIssuers)
            {
                supportingAuthenticators.Add(new RsaSecurityTokenAuthenticator());
            }

            outOfBandTokenResolver = (outOfBandTokens.Count > 0) ? SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(outOfBandTokens), false) : null;

            SamlSecurityTokenAuthenticator ssta;

            if ((recipientRequirement.SecurityBindingElement == null) || (recipientRequirement.SecurityBindingElement.LocalServiceSettings == null))
            {
                ssta = new SamlSecurityTokenAuthenticator(supportingAuthenticators);
            }
            else
            {
                ssta = new SamlSecurityTokenAuthenticator(supportingAuthenticators, recipientRequirement.SecurityBindingElement.LocalServiceSettings.MaxClockSkew);
            }

            // set audience uri restrictions
            ssta.AudienceUriMode = parent.IssuedTokenAuthentication.AudienceUriMode;
            IList <string> allowedAudienceUris = ssta.AllowedAudienceUris;

            if (parent.IssuedTokenAuthentication.AllowedAudienceUris != null)
            {
                for (int i = 0; i < parent.IssuedTokenAuthentication.AllowedAudienceUris.Count; i++)
                {
                    allowedAudienceUris.Add(parent.IssuedTokenAuthentication.AllowedAudienceUris[i]);
                }
            }

            if (recipientRequirement.ListenUri != null)
            {
                allowedAudienceUris.Add(recipientRequirement.ListenUri.AbsoluteUri);
            }

            return(ssta);
        }
Exemplo n.º 28
0
 SecurityTokenResolver GetResolver(bool canMatchLocalId, params SecurityToken [] tokens)
 {
     return(SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken> (tokens), canMatchLocalId));
 }
Exemplo n.º 29
0
        /// <summary>
        /// Executed when the authentication should be done.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        private void context_AuthenticateRequest(object sender, EventArgs e)
        {
            // Get the request.
            var request = ((HttpApplication)sender).Request;

            // The redirect back from the security token service is done using a POST method. Hence
            // abort processing of the current request, if it was not sent using POST.
            if (request.HttpMethod != "POST")
            {
                return;
            }

            // Check whether the request contains sign in data.
            if (request.Form["wa"] != WSFederationConstants.Actions.SignIn ||
                request.Form["wresult"].IsNullOrEmpty())
            {
                return;
            }

            // Otherwise, get the security token which is attached to the request, process it and
            // convert it to a principal. First, set up the federatec authentication module.
            var fam =
                new WSFederationAuthenticationModule
            {
                ServiceConfiguration =
                    new ServiceConfiguration
                {
                    AudienceRestriction       = { AudienceMode = AudienceUriMode.Never },
                    CertificateValidationMode =
                        X509CertificateValidationMode.Custom,
                    CertificateValidator = new CertificateValidator(c => true),
                    IssuerNameRegistry   = new X509CertificateIssuerNameRegistry()
                }
            };

            // Prepare the decryption by injecting the certificate to the service token resolver.
            var certificates =
                new List <SecurityToken>
            {
                new X509SecurityToken(
                    this.Container.Resolve <ICertificateManager>().GetEncryptingCertificate())
            };
            var encryptedSecurityTokenHandler =
                (from handler in fam.ServiceConfiguration.SecurityTokenHandlers
                 where handler is EncryptedSecurityTokenHandler
                 select handler).First() as EncryptedSecurityTokenHandler;

            encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), false);

            // Get the security token from the request.
            var securityToken = fam.GetSecurityToken(request);

            // Validate the token and convert it to a collection of claims.
            var claims = fam.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(securityToken);

            // Create a principal from the claims.
            IClaimsPrincipal principal = new ClaimsPrincipal(claims);

            // Set the current principal.
            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal  = principal;
        }
        /// <summary>
        /// Reads and validates a well fromed Saml2 token.
        /// </summary>
        /// <param name="securityToken">A Saml2 token.</param>
        /// <param name="validationParameters">Contains data and information needed for validation.</param>
        /// <param name="validatedToken">The <see cref="SamlSecurityToken"/> that was validated.</param>
        /// <exception cref="ArgumentNullException">'securityToken' is null or whitespace.</exception>
        /// <exception cref="ArgumentNullException">'validationParameters' is null.</exception>
        /// <exception cref="ArgumentException">'securityToken.Length' > <see cref="MaximumTokenSizeInBytes"/>.</exception>
        /// <returns>A <see cref="ClaimsPrincipal"/> generated from the claims in the Saml2 securityToken.</returns>
        public virtual ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;
            if (string.IsNullOrWhiteSpace(securityToken))
            {
                throw new ArgumentNullException("securityToken");
            }

            if (validationParameters == null)
            {
                throw new ArgumentNullException("validationParameters");
            }

            if (securityToken.Length > MaximumTokenSizeInBytes)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10209, securityToken.Length, MaximumTokenSizeInBytes));
            }

            Saml2SecurityToken samlToken;

            using (StringReader sr = new StringReader(securityToken))
            {
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)))
                {
                    samlToken = (new Saml2Handler()
                    {
                        Configuration = new SecurityTokenHandlerConfiguration
                        {
                            IssuerTokenResolver = new SecurityKeyResolver(securityToken, validationParameters),
                            MaxClockSkew = validationParameters.ClockSkew,
                            ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(validationParameters.ClientDecryptionTokens, true),
                        }
                    }).ReadToken(reader) as Saml2SecurityToken;
                }
            }

            if (samlToken.IssuerToken == null && validationParameters.RequireSignedTokens)
            {
                throw new SecurityTokenValidationException(ErrorMessages.IDX10213);
            }

            if (samlToken.Assertion == null)
            {
                throw new ArgumentException(ErrorMessages.IDX10202);
            }

            DateTime?notBefore = null;
            DateTime?expires   = null;

            if (samlToken.Assertion.Conditions != null)
            {
                notBefore = samlToken.Assertion.Conditions.NotBefore;
                expires   = samlToken.Assertion.Conditions.NotOnOrAfter;
            }

            Validators.ValidateTokenReplay(securityToken, expires, validationParameters);

            if (validationParameters.ValidateLifetime)
            {
                if (validationParameters.LifetimeValidator != null)
                {
                    if (!validationParameters.LifetimeValidator(notBefore: notBefore, expires: expires, securityToken: samlToken, validationParameters: validationParameters))
                    {
                        throw new SecurityTokenInvalidLifetimeException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10230, securityToken));
                    }
                }
                else
                {
                    ValidateLifetime(notBefore: notBefore, expires: expires, securityToken: samlToken, validationParameters: validationParameters);
                }
            }

            // TODO
            // need to validate   ValidateConfirmationData(subjectConfirmation.SubjectConfirmationData);

            if (validationParameters.ValidateAudience)
            {
                List <string> audiences = new List <string>();
                if (samlToken.Assertion.Conditions != null && samlToken.Assertion.Conditions.AudienceRestrictions != null)
                {
                    foreach (Saml2AudienceRestriction restriction in samlToken.Assertion.Conditions.AudienceRestrictions)
                    {
                        if (restriction == null)
                        {
                            continue;
                        }

                        foreach (Uri uri in restriction.Audiences)
                        {
                            if (uri == null)
                            {
                                continue;
                            }

                            audiences.Add(uri.OriginalString);
                        }
                    }
                }


                if (validationParameters.AudienceValidator != null)
                {
                    if (!validationParameters.AudienceValidator(audiences, samlToken, validationParameters))
                    {
                        throw new SecurityTokenInvalidAudienceException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10231, securityToken));
                    }
                }
                else
                {
                    ValidateAudience(audiences, samlToken, validationParameters);
                }
            }

            string issuer = samlToken.Assertion.Issuer != null ? samlToken.Assertion.Issuer.Value : null;

            if (validationParameters.ValidateIssuer)
            {
                if (validationParameters.IssuerValidator != null)
                {
                    issuer = validationParameters.IssuerValidator(issuer, samlToken, validationParameters);
                }
                else
                {
                    issuer = ValidateIssuer(issuer, samlToken, validationParameters);
                }
            }

            if (samlToken.IssuerToken != null)
            {
                ValidateIssuerSecurityKey(samlToken.IssuerToken.SecurityKeys[0], samlToken, validationParameters);
            }

            ClaimsIdentity identity = CreateClaimsIdentity(samlToken, issuer, validationParameters);

            if (validationParameters.SaveSigninToken)
            {
                identity.BootstrapContext = new BootstrapContext(securityToken);
            }

            validatedToken = samlToken;
            return(new ClaimsPrincipal(identity));
        }