示例#1
0
        protected virtual bool ValidateAudienceRestriction(SamlAudienceRestrictionCondition audienceRestrictionCondition)
        {
            for (int i = 0; i < audienceRestrictionCondition.Audiences.Count; i++)
            {
                if (audienceRestrictionCondition.Audiences[i] == null)
                {
                    continue;
                }

                for (int j = 0; j < this.allowedAudienceUris.Count; j++)
                {
                    if (StringComparer.Ordinal.Compare(audienceRestrictionCondition.Audiences[i].AbsoluteUri, this.allowedAudienceUris[j]) == 0)
                    {
                        return(true);
                    }
                    else if (Uri.IsWellFormedUriString(this.allowedAudienceUris[j], UriKind.Absolute))
                    {
                        Uri uri = new Uri(this.allowedAudienceUris[j]);
                        if (audienceRestrictionCondition.Audiences[i].Equals(uri))
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
示例#2
0
        /// <summary>
        /// Token Authentication.  Translates the decrypted data into a AuthContext.
        /// </summary>
        /// <param name="reader">The token XML reader.</param>
        /// <param name="audience">The audience that the token must be scoped for.
        /// Use <c>null</c> to indicate any audience is acceptable.</param>
        /// <returns>
        /// The authorization context carried by the token.
        /// </returns>
        internal static AuthorizationContext AuthenticateToken(XmlReader reader, Uri audience)
        {
            Contract.Ensures(Contract.Result <AuthorizationContext>() != null);

            // Extensibility Point:
            // in order to accept different token types, you would need to add additional
            // code to create an authenticationcontext from the security token.
            // This code only supports SamlSecurityToken objects.
            SamlSecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null) as SamlSecurityToken;

            if (null == token)
            {
                throw new InformationCardException("Unable to read security token");
            }

            ////if (null != token.SecurityKeys && token.SecurityKeys.Count > 0)
            ////    throw new InformationCardException("Token Security Keys Exist");

            if (audience == null)
            {
                Logger.InfoCard.Warn("SAML token Audience checking will be skipped.");
            }
            else
            {
                if (token.Assertion.Conditions != null &&
                    token.Assertion.Conditions.Conditions != null)
                {
                    foreach (SamlCondition condition in token.Assertion.Conditions.Conditions)
                    {
                        SamlAudienceRestrictionCondition audienceCondition = condition as SamlAudienceRestrictionCondition;

                        if (audienceCondition != null)
                        {
                            Logger.InfoCard.DebugFormat("SAML token audience(s): {0}", audienceCondition.Audiences.ToStringDeferred());
                            bool match = audienceCondition.Audiences.Contains(audience);

                            if (!match && Logger.InfoCard.IsErrorEnabled)
                            {
                                Logger.InfoCard.ErrorFormat("Expected SAML token audience of {0} but found {1}.", audience.AbsoluteUri, audienceCondition.Audiences.Select(aud => aud.AbsoluteUri).ToStringDeferred());
                            }

                            // The token is invalid if any condition is not valid.
                            // An audience restriction condition is valid if any audience
                            // matches the Relying Party.
                            ErrorUtilities.VerifyInfoCard(match, InfoCardStrings.AudienceMismatch);
                        }
                    }
                }
            }
            var samlAuthenticator = new SamlSecurityTokenAuthenticator(
                new List <SecurityTokenAuthenticator>(
                    new SecurityTokenAuthenticator[] {
                new RsaSecurityTokenAuthenticator(),
                new X509SecurityTokenAuthenticator(),
            }),
                MaximumClockSkew);

            return(AuthorizationContext.CreateDefaultAuthorizationContext(samlAuthenticator.ValidateToken(token)));
        }
示例#3
0
        /// <summary>
        /// Token Authentication. Translates the decrypted data into a AuthContext
        /// 
        /// This method makes a strong assumption that the decrypted token in in UTF-8 format.
        /// </summary>
        /// <param name="decryptedTokenData">Decrypted token</param>
        public static AuthorizationContext AuthenticateToken(byte[] decryptedTokenData)
        {
            string t = Encoding.UTF8.GetString(decryptedTokenData);
            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedTokenData), Encoding.UTF8));

            // Extensibility Point:
            // in order to accept different token types, you would need to add additional 
            // code to create an authenticationcontext from the security token. 
            // This code only supports SamlSecurityToken objects.
            SamlSecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null) as SamlSecurityToken;

            if( null == token )
                throw new InformationCardException("Unable to read security token");

            if (null != token.SecurityKeys && token.SecurityKeys.Count > 0)
                throw new InformationCardException("Token Security Keys Exist");

            if (null != _audience &&
                 null != token.Assertion.Conditions &&
                 null != token.Assertion.Conditions.Conditions)
            {
                foreach (SamlCondition condition in token.Assertion.Conditions.Conditions)
                {
                    SamlAudienceRestrictionCondition audienceCondition = condition as SamlAudienceRestrictionCondition;

                    if (null != audienceCondition)
                    {
                        bool match = false;

                        foreach (Uri audience in audienceCondition.Audiences)
                        {
                            match = audience.Equals(_audience);
                            if (match) break;
                        }

                        //
                        // The token is invalid if any condition is not valid. 
                        // An audience restriction condition is valid if any audience 
                        // matches the Relying Party.
                        //
                        if (!match)
                        {
                            throw new InformationCardException("The token is invalid: The audience restrictions does not match the Relying Party.");
                        }
                    }
                }
            }
            /*SamlSecurityTokenAuthenticator SamlAuthenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                            new SecurityTokenAuthenticator[]{
                                                new RsaSecurityTokenAuthenticator(),
                                                new X509SecurityTokenAuthenticator() }), MaximumTokenSkew);*/
            SamlSecurityTokenAuthenticator SamlAuthenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                            new SecurityTokenAuthenticator[]{
                                                new RsaSecurityTokenAuthenticator(),
                                                new X509SecurityTokenAuthenticator(X509CertificateValidator.None) }), MaximumTokenSkew);

            return AuthorizationContext.CreateDefaultAuthorizationContext(SamlAuthenticator.ValidateToken(token));
        }
        public void WriteXmlNoAudience()
        {
            SamlAudienceRestrictionCondition c = new SamlAudienceRestrictionCondition();

            StringWriter sw = new StringWriter();

            using (XmlDictionaryWriter dw = CreateWriter(sw)) {
                c.WriteXml(dw, new SamlSerializer(), null);
            }
        }
        public void WriteXml1()
        {
            SamlAudienceRestrictionCondition c = new SamlAudienceRestrictionCondition(new Uri [] { new Uri("urn:myAudience") });

            StringWriter sw = new StringWriter();

            using (XmlDictionaryWriter dw = CreateWriter(sw)) {
                c.WriteXml(dw, new SamlSerializer(), null);
            }
            Assert.AreEqual(String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:AudienceRestrictionCondition xmlns:saml=\"{0}\"><saml:Audience>urn:myAudience</saml:Audience></saml:AudienceRestrictionCondition>", SamlConstants.Namespace), sw.ToString());
        }
示例#6
0
        public void CompareSamlAudienceRestrictionConditions()
        {
            TestUtilities.WriteHeader($"{this}.CompareSamlAudienceRestrictionConditions", true);
            var context        = new CompareContext($"{this}.CompareSamlAudienceRestrictionConditions");
            var samlCondition1 = new SamlAudienceRestrictionCondition(new Uri(Default.Audiences.ElementAt(0)));
            var samlCondition2 = new SamlAudienceRestrictionCondition(new Uri(Default.Audiences.ElementAt(1)));

            IdentityComparer.AreEqual(samlCondition1, samlCondition2, context);

            Assert.True(context.Diffs.Count(s => s == "Audiences:") == 1);
        }
示例#7
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SamlSecurityToken samlToken = token as SamlSecurityToken;

            if (samlToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlTokenAuthenticatorCanOnlyProcessSamlTokens, token.GetType().ToString())));
            }

            if (samlToken.Assertion.Signature == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlTokenMissingSignature)));
            }

            if (!this.IsCurrentlyTimeEffective(samlToken))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLTokenTimeInvalid, DateTime.UtcNow.ToUniversalTime(), samlToken.ValidFrom.ToString(), samlToken.ValidTo.ToString())));
            }

            if (samlToken.Assertion.SigningToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlSigningTokenMissing)));
            }

            // Build the Issuer ClaimSet for this Saml token.
            ClaimSet issuer         = null;
            bool     canBeValidated = false;

            for (int i = 0; i < this.supportingAuthenticators.Count; ++i)
            {
                canBeValidated = this.supportingAuthenticators[i].CanValidateToken(samlToken.Assertion.SigningToken);
                if (canBeValidated)
                {
                    break;
                }
            }
            if (!canBeValidated)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlInvalidSigningToken)));
            }
            issuer = ResolveClaimSet(samlToken.Assertion.SigningToken) ?? ClaimSet.Anonymous;

            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();

            for (int i = 0; i < samlToken.Assertion.Statements.Count; ++i)
            {
                policies.Add(samlToken.Assertion.Statements[i].CreatePolicy(issuer, this));
            }


            // Check AudienceUri if required
            // AudienceUriMode != Never - don't need to check can only be one of three
            // AudienceUriMode == Always
            // AudienceUriMode == BearerKey and there are no proof keys
            //
            if ((this.audienceUriMode == AudienceUriMode.Always) ||
                (this.audienceUriMode == AudienceUriMode.BearerKeyOnly) && (samlToken.SecurityKeys.Count < 1))
            {
                // throws if not found.
                bool foundAudienceCondition = false;
                if (this.allowedAudienceUris == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceUrisNotFound)));
                }

                for (int i = 0; i < samlToken.Assertion.Conditions.Conditions.Count; i++)
                {
                    SamlAudienceRestrictionCondition audienceCondition = samlToken.Assertion.Conditions.Conditions[i] as SamlAudienceRestrictionCondition;
                    if (audienceCondition == null)
                    {
                        continue;
                    }

                    foundAudienceCondition = true;
                    if (!ValidateAudienceRestriction(audienceCondition))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceUriValidationFailed)));
                    }
                }

                if (!foundAudienceCondition)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceUriValidationFailed)));
                }
            }

            return(policies.AsReadOnly());
        }
        /// <summary>
        /// Reads and validates a well formed <see cref="SamlSecurityToken"/>.
        /// </summary>
        /// <param name="securityToken">A string containing a well formed securityToken.</param>
        /// <param name="validationParameters">Contains data and information needed for validation.</param>
        /// <param name="validatedToken">The <see cref="Saml2SecurityToken"/> that was validated.</param>
        /// <exception cref="ArgumentNullException">'securityToken' is null or whitespace.</exception>
        /// <exception cref="ArgumentNullException">'validationParameters' is null.</exception>
        /// <exception cref="SecurityTokenException">'securityToken.Length' > <see cref="MaximumTokenSizeInBytes"/>.</exception>
        /// <returns>A <see cref="ClaimsPrincipal"/> generated from the claims in the Saml securityToken.</returns>
        public virtual ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            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));
            }

            // Calling System.IdentityModel.Tokens.SamlSecurityTokenHandler requires Configuration and IssuerTokenResolver be set.
            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerTokenResolver = new SecurityKeyResolver(securityToken, validationParameters),
                MaxClockSkew        = validationParameters.ClockSkew,
            };

            SamlSecurityToken samlToken;

            using (StringReader sr = new StringReader(securityToken))
            {
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)))
                {
                    samlToken = ReadToken(reader, validationParameters) as SamlSecurityToken;
                }
            }

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

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

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

            if (validationParameters.ValidateAudience)
            {
                List <string> audiences = new List <string>();
                if (samlToken.Assertion.Conditions != null && samlToken.Assertion.Conditions.Conditions != null)
                {
                    foreach (SamlCondition condition in samlToken.Assertion.Conditions.Conditions)
                    {
                        SamlAudienceRestrictionCondition audienceRestriction = condition as SamlAudienceRestrictionCondition;
                        if (null == audienceRestriction)
                        {
                            continue;
                        }

                        foreach (Uri uri in audienceRestriction.Audiences)
                        {
                            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 = null;

            issuer = samlToken.Assertion.Issuer == null ? null : samlToken.Assertion.Issuer;

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

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

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

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

            validatedToken = samlToken;
            return(new ClaimsPrincipal(identity));
        }
示例#9
0
        /// <summary>
        /// Reads and validates a well formed <see cref="SamlSecurityToken"/>.
        /// </summary>
        /// <param name="securityToken">A string containing a well formed securityToken.</param>
        /// <param name="validationParameters">Contains data and information needed for validation.</param>
        /// <param name="validatedToken">The <see cref="Saml2SecurityToken"/> that was validated.</param>
        /// <exception cref="ArgumentNullException">'securityToken' is null or whitespace.</exception>
        /// <exception cref="ArgumentNullException">'validationParameters' is null.</exception>
        /// <exception cref="SecurityTokenException">'securityToken.Length' > <see cref="MaximumTokenSizeInBytes"/>.</exception>
        /// <returns>A <see cref="ClaimsPrincipal"/> generated from the claims in the Saml securityToken.</returns>
        public virtual ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            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));
            }

            SecurityKeyResolver issuerTokenResolver = new SecurityKeyResolver(securityToken, validationParameters);

            // Calling System.IdentityModel.Tokens.SamlSecurityTokenHandler requires Configuration and IssuerTokenResolver be set.
            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerTokenResolver = issuerTokenResolver,
                MaxClockSkew        = validationParameters.ClockSkew,
            };

            try
            {
                SamlSecurityToken samlToken;
                using (StringReader sr = new StringReader(securityToken))
                {
                    using (XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)))
                    {
                        samlToken = ReadToken(reader, validationParameters) as SamlSecurityToken;
                    }
                }

                if (samlToken == null)
                {
                    throw new SecurityTokenValidationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10201, securityToken));
                }

                if (samlToken.Assertion == null)
                {
                    throw new SecurityTokenValidationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10202, securityToken));
                }

                if (samlToken.Assertion.SigningToken == null && validationParameters.RequireSignedTokens)
                {
                    throw new SecurityTokenValidationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10213, securityToken));
                }

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

                if (validationParameters.ValidateAudience)
                {
                    List <string> audiences = new List <string>();
                    if (samlToken.Assertion.Conditions != null && samlToken.Assertion.Conditions.Conditions != null)
                    {
                        foreach (SamlCondition condition in samlToken.Assertion.Conditions.Conditions)
                        {
                            SamlAudienceRestrictionCondition audienceRestriction = condition as SamlAudienceRestrictionCondition;
                            if (null == audienceRestriction)
                            {
                                continue;
                            }

                            foreach (Uri uri in audienceRestriction.Audiences)
                            {
                                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 = null;
                issuer = samlToken.Assertion.Issuer == null ? null : samlToken.Assertion.Issuer;

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

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

                ClaimsIdentity identity = CreateClaimsIdentity(samlToken, issuer, validationParameters);
                if (validationParameters.SaveSigninToken)
                {
                    identity.BootstrapContext = new BootstrapContext(securityToken);
                }

                validatedToken = samlToken;
                return(new ClaimsPrincipal(identity));
            }
            catch (SignatureVerificationFailedException ex)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(securityToken);
                XmlNodeList keyInfoList = xmlDoc.GetElementsByTagName(SamlConstants.KeyInfo);
                if (keyInfoList.Count > 0 &&
                    (validationParameters.IssuerSigningKey != null ||
                     validationParameters.IssuerSigningKeys != null ||
                     validationParameters.IssuerSigningToken != null ||
                     validationParameters.IssuerSigningTokens != null ||
                     validationParameters.IssuerSigningKeyResolver != null))
                {
                    XmlNode keyInfoNode = keyInfoList.Item(0);
                    if (String.IsNullOrEmpty(keyInfoNode.InnerXml))
                    {
                        // KeyInfo element is empty.
                        throw;
                    }
                    else
                    {
                        if (issuerTokenResolver.IsKeyMatched)
                        {
                            // keyInfo in token matched with key(s) in validationParameters. This usually means the token was compromised.
                            throw;
                        }
                        else
                        {
                            // KeyInfo in token didn't match with key(s) in validationParameters. This means the user should refresh the key material.
                            throw new SecurityTokenSignatureKeyNotFoundException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10506, securityToken), ex);
                        }
                    }
                }
                else
                {
                    // Missing KeyInfo element or validation parameters' SigningKey/SigningKeys/SigningToken/SigningTokens/IssuerSigningKeyResolver.
                    throw;
                }
            }
        }
示例#10
0
        private SamlAssertion CreateSamlAssertion(SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier)
        {
            Claim claim = base.ClientCredentials.Claims.FirstOrDefault((Claim c) => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");

            if (claim == null)
            {
                throw new ArgumentException("At least one NameIdentifier/Identity claim must be present in the claimset", "ClaimsClientCredentials.Claims");
            }
            SamlSubject samlSubject = new SamlSubject
            {
                NameFormat    = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
                Name          = claim.Value,
                KeyIdentifier = proofKeyIdentifier
            };

            samlSubject.ConfirmationMethods.Add(SamlConstants.HolderOfKey);
            IEnumerable <SamlAttribute> enumerable = from c in base.ClientCredentials.Claims.Except(new Claim[]
            {
                claim
            })
                                                     select new SamlAttribute(SamlConstants.Namespace, c.Type, new string[]
            {
                c.Value
            });

            if (base.ClientCredentials.Claims.FirstOrDefault((Claim c) => c.Type == "http://www.tridion.com/2009/08/directoryservice/claims/directoryServiceName") == null)
            {
                SamlAttribute samlAttribute = new SamlAttribute(SamlConstants.Namespace, "http://www.tridion.com/2009/08/directoryservice/claims/directoryServiceName", new string[]
                {
                    claim.Issuer
                });
                enumerable = enumerable.Concat(new SamlAttribute[]
                {
                    samlAttribute
                });
            }
            DateTime      utcNow        = DateTime.UtcNow;
            SamlAssertion samlAssertion = new SamlAssertion
            {
                AssertionId        = "_" + Guid.NewGuid(),
                Issuer             = claim.Issuer,
                IssueInstant       = utcNow,
                Advice             = new SamlAdvice(),
                SigningCredentials = new SigningCredentials(signatureKey, base.SecurityAlgorithmSuite.DefaultAsymmetricSignatureAlgorithm, base.SecurityAlgorithmSuite.DefaultDigestAlgorithm, signatureKeyIdentifier)
            };

            samlAssertion.Statements.Add(new SamlAttributeStatement(samlSubject, enumerable));
            if (base.ClientCredentials.AudienceUris != null)
            {
                IEnumerable <SamlCondition> conditions = new SamlAudienceRestrictionCondition[]
                {
                    new SamlAudienceRestrictionCondition(base.ClientCredentials.AudienceUris)
                };
                samlAssertion.Conditions = new SamlConditions(utcNow, utcNow + base.TokenValidityTimeSpan, conditions);
            }
            else
            {
                samlAssertion.Conditions = new SamlConditions(utcNow, utcNow + base.TokenValidityTimeSpan);
            }
            return(samlAssertion);
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }
            SamlSecurityToken token2 = token as SamlSecurityToken;

            if (token2 == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SamlTokenAuthenticatorCanOnlyProcessSamlTokens", new object[] { token.GetType().ToString() })));
            }
            if (token2.Assertion.Signature == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SamlTokenMissingSignature")));
            }
            if (!this.IsCurrentlyTimeEffective(token2))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLTokenTimeInvalid", new object[] { DateTime.UtcNow.ToUniversalTime(), token2.ValidFrom.ToString(), token2.ValidTo.ToString() })));
            }
            if (token2.Assertion.SigningToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SamlSigningTokenMissing")));
            }
            ClaimSet issuer = null;
            bool     flag   = false;

            for (int i = 0; i < this.supportingAuthenticators.Count; i++)
            {
                flag = this.supportingAuthenticators[i].CanValidateToken(token2.Assertion.SigningToken);
                if (flag)
                {
                    break;
                }
            }
            if (!flag)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SamlInvalidSigningToken")));
            }
            issuer = this.ResolveClaimSet(token2.Assertion.SigningToken) ?? ClaimSet.Anonymous;
            List <IAuthorizationPolicy> list = new List <IAuthorizationPolicy>();

            for (int j = 0; j < token2.Assertion.Statements.Count; j++)
            {
                list.Add(token2.Assertion.Statements[j].CreatePolicy(issuer, this));
            }
            if ((this.audienceUriMode == System.IdentityModel.Selectors.AudienceUriMode.Always) || ((this.audienceUriMode == System.IdentityModel.Selectors.AudienceUriMode.BearerKeyOnly) && (token2.SecurityKeys.Count < 1)))
            {
                bool flag2 = false;
                if (this.allowedAudienceUris == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAudienceUrisNotFound")));
                }
                for (int k = 0; k < token2.Assertion.Conditions.Conditions.Count; k++)
                {
                    SamlAudienceRestrictionCondition audienceRestrictionCondition = token2.Assertion.Conditions.Conditions[k] as SamlAudienceRestrictionCondition;
                    if (audienceRestrictionCondition != null)
                    {
                        flag2 = true;
                        if (!this.ValidateAudienceRestriction(audienceRestrictionCondition))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAudienceUriValidationFailed")));
                        }
                    }
                }
                if (!flag2)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAudienceUriValidationFailed")));
                }
            }
            return(list.AsReadOnly());
        }