protected void TraceTokenValidationFailure(SecurityToken token, string errorMessage)
 {
     if (TD.TokenValidationFailureIsEnabled())
     {
         TD.TokenValidationFailure(this.EventTraceActivity, token.GetType().ToString(), token.Id, errorMessage);
     }
 }
        /// <summary>
        /// Gets the name of the issuer.
        /// </summary>
        /// <param name="securityToken">The security token.</param>
        /// <returns></returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                throw new ArgumentNullException("securityToken");
            }

            var x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                var issuer = x509Token.Certificate.Thumbprint;
                Debug.WriteLine("Certificate thumbprint: " + issuer);

                return issuer;
            }
            
            var rsaToken = securityToken as RsaSecurityToken;
            if (rsaToken != null)
            {
                var issuer = rsaToken.Rsa.ToXmlString(false);
                Debug.WriteLine("RSA: " + issuer);

                return issuer;
            }

            throw new SecurityTokenException(securityToken.GetType().FullName);
        }
        /// <summary>
        /// Gets the name of the issuer.
        /// </summary>
        /// <param name="securityToken">The security token.</param>
        /// <returns></returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                Tracing.Error("SimpleIssuerNameRegistry: securityToken is null");
                throw new ArgumentNullException("securityToken");
            }

            X509SecurityToken token = securityToken as X509SecurityToken;
            if (token != null)
            {
                Tracing.Information("SimpleIssuerNameRegistry: X509 SubjectName: " + token.Certificate.SubjectName.Name);
                Tracing.Information("SimpleIssuerNameRegistry: X509 Thumbprint : " + token.Certificate.Thumbprint);
                return token.Certificate.Thumbprint;
            }
            
            RsaSecurityToken token2 = securityToken as RsaSecurityToken;
            if (token2 == null)
            {
                throw new SecurityTokenException(securityToken.GetType().FullName);
            }

            Tracing.Information("SimpleIssuerNameRegistry: RSA Key: " + token2.Rsa.ToXmlString(false));
            return token2.Rsa.ToXmlString(false);
        }
 protected void TraceTokenValidationSuccess(SecurityToken token)
 {
     if (TD.TokenValidationSuccessIsEnabled())
     {
         TD.TokenValidationSuccess(this.EventTraceActivity, token.GetType().ToString(), token.Id);
     }
 }
        public ReadOnlyCollection<IAuthorizationPolicy> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }
            if (!CanValidateToken(token))
            {
                // warning 56506: Parameter 'token' to this public method must be validated:  A null-dereference can occur here.
#pragma warning suppress 56506
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.CannotValidateSecurityTokenType, this, token.GetType())));
            }

            EventTraceActivity eventTraceActivity = null;
            string tokenType = null;

            if (TD.TokenValidationStartedIsEnabled())
            {
                eventTraceActivity = eventTraceActivity ?? EventTraceActivity.GetFromThreadOrCreate();
                tokenType = tokenType ?? token.GetType().ToString();
                TD.TokenValidationStarted(eventTraceActivity, tokenType, token.Id);
            }

            ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = ValidateTokenCore(token);
            if (authorizationPolicies == null)
            {
                string errorMsg = SR.GetString(SR.CannotValidateSecurityTokenType, this, token.GetType());
                if (TD.TokenValidationFailureIsEnabled())
                {
                    eventTraceActivity = eventTraceActivity ?? EventTraceActivity.GetFromThreadOrCreate();
                    tokenType = tokenType ?? token.GetType().ToString();
                    TD.TokenValidationFailure(eventTraceActivity, tokenType, token.Id, errorMsg);
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(errorMsg));
            }

            if (TD.TokenValidationSuccessIsEnabled())
            {
                eventTraceActivity = eventTraceActivity ?? EventTraceActivity.GetFromThreadOrCreate();
                tokenType = tokenType ?? token.GetType().ToString();
                TD.TokenValidationSuccess(eventTraceActivity, tokenType, token.Id);
            }

            return authorizationPolicies;
        }
 public ReadOnlyCollection<IAuthorizationPolicy> ValidateToken(SecurityToken token)
 {
     if (token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
     }
     if (!this.CanValidateToken(token))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(System.IdentityModel.SR.GetString("CannotValidateSecurityTokenType", new object[] { this, token.GetType() })));
     }
     ReadOnlyCollection<IAuthorizationPolicy> onlys = this.ValidateTokenCore(token);
     if (onlys == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(System.IdentityModel.SR.GetString("CannotValidateSecurityTokenType", new object[] { this, token.GetType() })));
     }
     return onlys;
 }
 // helpers
 static X509SecurityToken ValidateToken(SecurityToken token)
 {
     X509SecurityToken result = token as X509SecurityToken;
     if (result == null && token != null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TokenProviderReturnedBadToken, token.GetType().ToString())));
     }
     return result;
 }
        protected override bool CanValidateTokenCore(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            return ((token.GetType() == _securityTokenHandler.TokenType) && (_securityTokenHandler.CanValidateToken));
        }
Exemplo n.º 9
0
        public ReadOnlyCollection<IAuthorizationPolicy> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }
            if (!CanValidateToken(token))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.Format(SR.CannotValidateSecurityTokenType, this, token.GetType())));
            }

            EventTraceActivity eventTraceActivity = null;
            string tokenType = null;

            if (WcfEventSource.Instance.TokenValidationStartedIsEnabled())
            {
                eventTraceActivity = eventTraceActivity ?? EventTraceActivity.GetFromThreadOrCreate();
                tokenType = tokenType ?? token.GetType().ToString();
                WcfEventSource.Instance.TokenValidationStarted(eventTraceActivity, tokenType, token.Id);
            }

            ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = ValidateTokenCore(token);
            if (authorizationPolicies == null)
            {
                string errorMsg = SR.Format(SR.CannotValidateSecurityTokenType, this, token.GetType());
                if (WcfEventSource.Instance.TokenValidationFailureIsEnabled())
                {
                    eventTraceActivity = eventTraceActivity ?? EventTraceActivity.GetFromThreadOrCreate();
                    tokenType = tokenType ?? token.GetType().ToString();
                    WcfEventSource.Instance.TokenValidationFailure(eventTraceActivity, tokenType, token.Id, errorMsg);
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(errorMsg));
            }

            if (WcfEventSource.Instance.TokenValidationSuccessIsEnabled())
            {
                eventTraceActivity = eventTraceActivity ?? EventTraceActivity.GetFromThreadOrCreate();
                tokenType = tokenType ?? token.GetType().ToString();
                WcfEventSource.Instance.TokenValidationSuccess(eventTraceActivity, tokenType, token.Id);
            }

            return authorizationPolicies;
        }
 X509SecurityToken ValidateX509Token(SecurityToken token)
 {
     X509SecurityToken result = token as X509SecurityToken;
     if (result == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TokenProviderReturnedBadToken, token == null ? "<null>" : token.GetType().ToString())));
     }
     SecurityUtils.EnsureCertificateCanDoKeyExchange(result.Certificate);
     return result;
 }
Exemplo n.º 11
0
        public SecurityTokenHandler this[SecurityToken token] {
            get {
                if (token == null)
                {
                    return(null);
                }

                return(this[token.GetType()]);
            }
        }
        public static ITokenVisualizer GetTokenVisualizer(SecurityToken token)
        {
            foreach (var factory in availableFactories)
            {
                if (factory.SupportedToken == token.GetType())
                {
                    return factory.GetTokenVisualizer(token);
                }
            }

            return null;
        }
 protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore( SecurityToken token )
 {
     if ( _wrappedSaml11SecurityTokenAuthenticator.CanValidateToken( token ) )
     {
         return _wrappedSaml11SecurityTokenAuthenticator.ValidateToken( token );
     }
     else if ( _wrappedSaml2SecurityTokenAuthenticator.CanValidateToken( token ) )
     {
         return _wrappedSaml2SecurityTokenAuthenticator.ValidateToken( token );
     }
     else
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException( SR.GetString( SR.ID4101, token.GetType().ToString() ) ) );
     }
 }
        /// <summary>
        /// Gets the name of the issuer.
        /// </summary>
        /// <param name="securityToken">The security token.</param>
        /// <returns></returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                throw new ArgumentNullException("securityToken");
            }

            X509SecurityToken token = securityToken as X509SecurityToken;
            if (token != null)
            {
                return token.Certificate.Issuer;
            }

            throw new SecurityTokenException(securityToken.GetType().FullName);
        }
        /// <summary>
        /// Serializes to XML a securityToken of the type handled by this instance.
        /// </summary>
        /// <param name="writer">The XML writer.</param>
        /// <param name="securityToken">A securityToken of type <see cref="TokenType"/>.</param>
        public override void WriteToken(XmlWriter writer, SecurityToken securityToken)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

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

            Saml2SecurityToken samlSecurityToken = securityToken as Saml2SecurityToken;
            if (samlSecurityToken == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10400, this.GetType(), typeof(SamlSecurityToken), securityToken.GetType()));
            }

            _smSaml2HandlerPrivateNeverSetAnyProperties.WriteToken(writer, securityToken);
        }
        /// <summary>
        /// Serializes to <see cref="Saml2SecurityToken"/> to a string.
        /// </summary>
        /// <param name="securityToken">A <see cref="Saml2SecurityToken"/>.</param>
        public override string WriteToken(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                throw new ArgumentNullException("securityToken");
            }

            Saml2SecurityToken samlSecurityToken = securityToken as Saml2SecurityToken;
            if (samlSecurityToken == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10400, this.GetType(), typeof(Saml2SecurityToken), securityToken.GetType()));
            }

            StringBuilder stringBuilder = new StringBuilder();
            using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
            {
                _smSaml2HandlerPrivateNeverSetAnyProperties.WriteToken(xmlWriter, securityToken);
                return stringBuilder.ToString();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Validates the lifetime of a <see cref="SecurityToken"/>.
        /// </summary>
        /// <param name="notBefore">The 'notBefore' time found in the <see cref="SecurityToken"/>.</param>
        /// <param name="expires">The 'expiration' time found in the <see cref="SecurityToken"/>.</param>
        /// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
        /// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
        /// <exception cref="ArgumentNullException"> if 'vaidationParameters' is null.</exception>
        /// <exception cref="SecurityTokenNoExpirationException"> if 'expires.HasValue' is false and <see cref="TokenValidationParameters.RequireExpirationTime"/> is true.</exception>
        /// <exception cref="SecurityTokenInvalidLifetimeException"> if 'notBefore' is &gt; 'expires'.</exception>
        /// <exception cref="SecurityTokenNotYetValidException"> if 'notBefore' is &gt; DateTime.UtcNow.</exception>
        /// <exception cref="SecurityTokenExpiredException"> if 'expires' is &lt; DateTime.UtcNow.</exception>
        /// <remarks>All time comparisons apply <see cref="TokenValidationParameters.ClockSkew"/>.</remarks>
        public static void ValidateLifetime(DateTime?notBefore, DateTime?expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
        {
            if (validationParameters == null)
            {
                throw new ArgumentNullException("validationParameters");
            }

            if (!validationParameters.ValidateLifetime)
            {
                return;
            }

            if (!expires.HasValue && validationParameters.RequireExpirationTime)
            {
                throw new SecurityTokenNoExpirationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10225, securityToken == null ? "null" : securityToken.GetType().ToString()));
            }

            if (notBefore.HasValue && expires.HasValue && (notBefore.Value > expires.Value))
            {
                throw new SecurityTokenInvalidLifetimeException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10224, notBefore.Value, expires.Value));
            }

            DateTime utcNow = DateTime.UtcNow;

            if (notBefore.HasValue && (notBefore.Value > DateTimeUtil.Add(utcNow, validationParameters.ClockSkew)))
            {
                throw new SecurityTokenNotYetValidException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10222, notBefore.Value, utcNow));
            }

            if (expires.HasValue && (expires.Value < DateTimeUtil.Add(utcNow, validationParameters.ClockSkew.Negate())))
            {
                throw new SecurityTokenExpiredException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10223, expires.Value, utcNow));
            }
        }
        /// <summary>
        /// Validates a <see cref="SessionSecurityToken"/>.
        /// </summary>
        /// <param name="token">The <see cref="SessionSecurityToken"/> to validate.</param>
        /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception>
        /// <exception cref="ArgumentException">The token is not assignable from <see cref="SessionSecurityToken"/>.</exception>
        public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SessionSecurityToken sessionToken = token as SessionSecurityToken;
            if (sessionToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4292, token.GetType().ToString(), this.GetType().ToString())));
            }

            try
            {
                if (DiagnosticUtility.ShouldTrace(TraceEventType.Verbose))
                {
                    TraceUtility.TraceEvent(
                        TraceEventType.Verbose,
                        TraceCode.Diagnostics,
                        SR.GetString(SR.TraceValidateToken),
                        new SecurityTraceRecordHelper.TokenTraceRecord(token),
                        null,
                        null);
                }

                this.ValidateSession(sessionToken);

                this.TraceTokenValidationSuccess(token);

                List<ClaimsIdentity> identitites = new List<ClaimsIdentity>(1);
                identitites.AddRange(sessionToken.ClaimsPrincipal.Identities);
                return identitites.AsReadOnly();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                this.TraceTokenValidationFailure(token, e.Message);
                throw e;
            }
        }
		protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause (
			SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
		{
			if (token == null)
				throw new ArgumentNullException ("token");

			if (referenceStyle == SecurityTokenReferenceStyle.Internal)
				return new LocalIdKeyIdentifierClause (token.Id, token.GetType ());

			switch (reference_style) {
			default:
				return token.CreateKeyIdentifierClause<X509IssuerSerialKeyIdentifierClause> ();
			case X509KeyIdentifierClauseType.Thumbprint:
				return token.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause> ();
			case X509KeyIdentifierClauseType.SubjectKeyIdentifier:
				return token.CreateKeyIdentifierClause<X509SubjectKeyIdentifierClause> ();
			case X509KeyIdentifierClauseType.RawDataKeyIdentifier:
				return token.CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause> ();
			case X509KeyIdentifierClauseType.Any:
				if (token.CanCreateKeyIdentifierClause<X509SubjectKeyIdentifierClause> ())
					goto case X509KeyIdentifierClauseType.SubjectKeyIdentifier;
				goto default;
			}
		}
 protected void TraceTokenValidationSuccess(SecurityToken token)
 {
     if (TD.TokenValidationSuccessIsEnabled())
     {
         TD.TokenValidationSuccess(this.EventTraceActivity, token.GetType().ToString(), token.Id);
     }
 }
Exemplo n.º 21
0
			bool TokenMatchesClause (SecurityToken token, SecurityKeyIdentifierClause clause)
			{
				if (token.MatchesKeyIdentifierClause (clause))
					return true;
				if (!match_local)
					return false;
				LocalIdKeyIdentifierClause l =
					clause as LocalIdKeyIdentifierClause;
				return l != null && l.Matches (token.Id, token.GetType ());
			}
        /// <summary>
        /// Validates a <see cref="SamlSecurityToken"/>.
        /// </summary>
        /// <param name="token">The <see cref="SamlSecurityToken"/> to validate.</param>
        /// <returns>The <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception>
        /// <exception cref="ArgumentException">The token is not assignable from <see cref="SamlSecurityToken"/>.</exception>
        /// <exception cref="InvalidOperationException">Configuration <see cref="SecurityTokenHandlerConfiguration"/>is null.</exception>
        /// <exception cref="ArgumentException">SamlSecurityToken.Assertion is null.</exception>
        /// <exception cref="SecurityTokenValidationException">Thrown if SamlSecurityToken.Assertion.SigningToken is null.</exception>
        /// <exception cref="SecurityTokenValidationException">Thrown if the certificate associated with the token issuer does not pass validation.</exception>
        public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SamlSecurityToken samlToken = token as SamlSecurityToken;
            if (samlToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID1033, token.GetType().ToString()));
            }

            if (this.Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            try
            {
                if (samlToken.Assertion == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID1034));
                }

                TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.Diagnostics, SR.GetString(SR.TraceValidateToken), new SecurityTraceRecordHelper.TokenTraceRecord(token), null, null);

                // Ensure token was signed and verified at some point
                if (samlToken.Assertion.SigningToken == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID4220)));
                }

                this.ValidateConditions(samlToken.Assertion.Conditions, _samlSecurityTokenRequirement.ShouldEnforceAudienceRestriction(this.Configuration.AudienceRestriction.AudienceMode, samlToken));

                // We need something like AudienceUriMode and have a setting on Configuration to allow extensibility and custom settings
                // By default we only check bearer tokens
                if (this.Configuration.DetectReplayedTokens)
                {
                    this.DetectReplayedToken(samlToken);
                }

                //
                // If the backing token is x509, validate trust
                //
                X509SecurityToken x509IssuerToken = samlToken.Assertion.SigningToken as X509SecurityToken;
                if (x509IssuerToken != null)
                {
                    try
                    {
                        CertificateValidator.Validate(x509IssuerToken.Certificate);
                    }
                    catch (SecurityTokenValidationException e)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID4257,
                                X509Util.GetCertificateId(x509IssuerToken.Certificate)), e));
                    }
                }

                //
                // Create the claims
                //
                ClaimsIdentity claimsIdentity = CreateClaims(samlToken);

                if (_samlSecurityTokenRequirement.MapToWindows)
                {
                    // TFS: 153865, [....] WindowsIdentity does not set Authtype. I don't think that authtype should be set here anyway.
                    // The authtype will be S4U (kerberos) it doesn't really matter that the upn arrived in a SAML token.
                    WindowsIdentity windowsIdentity = CreateWindowsIdentity(FindUpn(claimsIdentity));

                    // PARTIAL TRUST: will fail when adding claims, AddClaims is SecurityCritical.
                    windowsIdentity.AddClaims(claimsIdentity.Claims);
                    claimsIdentity = windowsIdentity;
                }

                if (this.Configuration.SaveBootstrapContext)
                {
                    claimsIdentity.BootstrapContext = new BootstrapContext(token, this);
                }

                this.TraceTokenValidationSuccess(token);

                List<ClaimsIdentity> identities = new List<ClaimsIdentity>(1);
                identities.Add(claimsIdentity);
                return identities.AsReadOnly();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                this.TraceTokenValidationFailure(token, e.Message);
                throw e;
            }
        }
        /// <summary>
        /// Validates a given token using the SecurityTokenHandlers.
        /// </summary>
        /// <param name="token">The SecurityToken to be validated.</param>
        /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        /// <exception cref="InvalidOperationException">A <see cref="SecurityTokenHandler"/> cannot be found that can validate the <see cref="SecurityToken"/>.</exception>
        public ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SecurityTokenHandler handler = this[token];

            if (null == handler || !handler.CanValidateToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4011, token.GetType())));
            }

            return(handler.ValidateToken(token));
        }
Exemplo n.º 24
0
 protected override bool CanWriteTokenCore(SecurityToken token)
 {
     for (int i = 0; i < _tokenEntries.Count; i++)
     {
         TokenEntry tokenEntry = _tokenEntries[i];
         if (tokenEntry.SupportsCore(token.GetType()))
             return true;
     }
     return false;
 }
Exemplo n.º 25
0
        public virtual List<SamlAttribute> GetClaims(SecurityToken samlToken)
        {
            //switch between Saml2SecurityToken and SamlSecurityToken

            if (typeof(SamlSecurityToken).IsAssignableFrom(samlToken.GetType()))
                return GetClaims((SamlSecurityToken)samlToken);

            if (typeof(Saml2SecurityToken).IsAssignableFrom(samlToken.GetType()))
                return GetClaims((Saml2SecurityToken)samlToken);

            throw new ArgumentException("Cannot GetClaims from the current passed SecurityToken type", "samlToken");
        }
        protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
        {
            bool wroteToken = false;
            XmlDictionaryWriter localWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);
            if (token.GetType() == typeof(ProviderBackedSecurityToken))
            {
                token = (token as ProviderBackedSecurityToken).Token;
            }
            for (int i = 0; i < this.tokenEntries.Count; i++)
            {
                TokenEntry tokenEntry = this.tokenEntries[i];
                if (tokenEntry.SupportsCore(token.GetType()))
                {
                    try
                    {
                        tokenEntry.WriteTokenCore(localWriter, token);
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (Exception e)
                    {
                        if (!ShouldWrapException(e))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ErrorSerializingSecurityToken), e));
                    }
                    wroteToken = true;
                    break;
                }
            }

            if (!wroteToken)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StandardsManagerCannotWriteObject, token.GetType())));

            localWriter.Flush();
        }
        /// <summary>
        /// Writes the <see cref="JwtSecurityToken"/> wrapped in a WS-Security BinarySecurityToken using the <see cref="XmlWriter"/>.
        /// </summary>
        /// <param name="writer"><see cref="XmlWriter"/> used to write token.</param>
        /// <param name="token">The <see cref="JwtSecurityToken"/> that will be written.</param>
        /// <exception cref="ArgumentNullException">'writer' is null.</exception>
        /// <exception cref="ArgumentNullException">'token' is null.</exception>
        /// <exception cref="ArgumentException">'token' is not a not <see cref="JwtSecurityToken"/>.</exception>
        /// <remarks>The <see cref="JwtSecurityToken"/> current contents are encoded. If <see cref="JwtSecurityToken.SigningCredentials"/> is not null, the encoding will contain a signature.</remarks>
        public override void WriteToken(XmlWriter writer, SecurityToken token)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

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

            if (!(token is JwtSecurityToken))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10226, GetType(), typeof(JwtSecurityToken), token.GetType()));
            }

            byte[] rawData = Encoding.UTF8.GetBytes(this.WriteToken(token));
            writer.WriteStartElement(WSSecurityConstantsInternal.Prefix, WSSecurityConstantsInternal.Elements.BinarySecurityToken, WSSecurityConstantsInternal.Namespace);
            if (token.Id != null)
            {
                writer.WriteAttributeString(WSSecurityConstantsInternal.Prefix, WSSecurityUtilityConstantsInternal.Attributes.Id, WSSecurityConstantsInternal.Namespace, token.Id);
            }

            writer.WriteAttributeString(WSSecurityConstantsInternal.Attributes.ValueType, null, JwtConstants.TokenTypeAlt);
            writer.WriteAttributeString(WSSecurityConstantsInternal.Attributes.EncodingType, null, WSSecurityConstantsInternal.Base64EncodingType);
            writer.WriteBase64(rawData, 0, rawData.Length);
            writer.WriteEndElement();
        }
 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();
 }
        /// <summary>
        /// Writes the <see cref="JwtSecurityToken"/> as a JSON Compact serialized format string.
        /// </summary>
        /// <param name="token"><see cref="JwtSecurityToken"/> to serialize.</param>
        /// <remarks>
        /// <para>If the <see cref="JwtSecurityToken.SigningCredentials"/> are not null, the encoding will contain a signature.</para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">'token' is null.</exception>
        /// <exception cref="ArgumentException">'token' is not a not <see cref="JwtSecurityToken"/>.</exception>
        /// <returns>The <see cref="JwtSecurityToken"/> as a signed (if <see cref="SigningCredentials"/> exist) encoded string.</returns>
        public override string WriteToken(SecurityToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            JwtSecurityToken jwt = token as JwtSecurityToken;
            if (jwt == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10706, GetType(), typeof(JwtSecurityToken), token.GetType()));
            }

            string signature = string.Empty;
            string signingInput = string.Concat(jwt.EncodedHeader, ".", jwt.EncodedPayload);

            if (jwt.SigningCredentials != null)
            {
                signature = Base64UrlEncoder.Encode(this.CreateSignature(signingInput, jwt.SigningCredentials.SigningKey, jwt.SigningCredentials.SignatureAlgorithm));
            }

            return string.Concat(signingInput, ".", signature);
        }
        /// <summary>
        /// Serializes the given SecurityToken to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter into which the token is serialized.</param>
        /// <param name="token">SecurityToken to be serialized.</param>
        /// <exception cref="ArgumentNullException">Input parameter 'writer' or 'token' is null.</exception>
        /// <exception cref="SecurityTokenException">The given 'token' is not a SamlSecurityToken.</exception>
        public override void WriteToken(XmlWriter writer, SecurityToken token)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

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

            SamlSecurityToken samlSecurityToken = token as SamlSecurityToken;
            if (samlSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4217, token.GetType(), typeof(SamlSecurityToken))));
            }

            WriteAssertion(writer, samlSecurityToken.Assertion);
        }
        /// <summary>
        /// Validates a <see cref="SessionSecurityToken"/>.
        /// </summary>
        /// <param name="token">The <see cref="SessionSecurityToken"/> to validate.</param>
        /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception>
        /// <exception cref="ArgumentException">The token is not assignable from <see cref="SessionSecurityToken"/>.</exception>
        public override ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SessionSecurityToken sessionToken = token as SessionSecurityToken;

            if (sessionToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4292, token.GetType().ToString(), this.GetType().ToString())));
            }

            try
            {
                if (DiagnosticUtility.ShouldTrace(TraceEventType.Verbose))
                {
                    TraceUtility.TraceEvent(
                        TraceEventType.Verbose,
                        TraceCode.Diagnostics,
                        SR.GetString(SR.TraceValidateToken),
                        new SecurityTraceRecordHelper.TokenTraceRecord(token),
                        null,
                        null);
                }

                this.ValidateSession(sessionToken);

                this.TraceTokenValidationSuccess(token);

                List <ClaimsIdentity> identitites = new List <ClaimsIdentity>(1);
                identitites.AddRange(sessionToken.ClaimsPrincipal.Identities);
                return(identitites.AsReadOnly());
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                this.TraceTokenValidationFailure(token, e.Message);
                throw e;
            }
        }
 protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
 {
     bool flag = false;
     XmlDictionaryWriter writer2 = XmlDictionaryWriter.CreateDictionaryWriter(writer);
     if (token.GetType() == typeof(ProviderBackedSecurityToken))
     {
         token = (token as ProviderBackedSecurityToken).Token;
     }
     for (int i = 0; i < this.tokenEntries.Count; i++)
     {
         TokenEntry entry = this.tokenEntries[i];
         if (entry.SupportsCore(token.GetType()))
         {
             try
             {
                 entry.WriteTokenCore(writer2, token);
             }
             catch (Exception exception)
             {
                 if (!this.ShouldWrapException(exception))
                 {
                     throw;
                 }
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("ErrorSerializingSecurityToken"), exception));
             }
             flag = true;
             break;
         }
     }
     if (!flag)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("StandardsManagerCannotWriteObject", new object[] { token.GetType() })));
     }
     writer2.Flush();
 }
 protected void TraceTokenValidationFailure(SecurityToken token, string errorMessage)
 {
     if (TD.TokenValidationFailureIsEnabled())
     {
         TD.TokenValidationFailure(this.EventTraceActivity, token.GetType().ToString(), token.Id, errorMessage);
     }
 }
        /// <summary>
        /// Throws if a token is detected as being replayed. If the token is not found, it is added to the 
        /// <see cref="TokenReplayCache" />.
        /// </summary>
        /// <param name="token">The token to detect for replay.</param>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        /// <exception cref="InvalidOperationException">Configuration or Configuration.TokenReplayCache property is null.</exception>
        /// <exception cref="ArgumentException">The input argument 'token' can not be cast as a 'Saml2SecurityToken'.</exception>
        /// <exception cref="SecurityTokenValidationException">The Saml2SecurityToken.Assertion.Id.Value is null or empty.</exception>
        /// <exception cref="SecurityTokenReplayDetectedException">The token is found in the <see cref="TokenReplayCache" />.</exception>
        /// <remarks>The default behavior is to only check tokens bearer tokens (tokens that do not have keys).</remarks>
        protected override void DetectReplayedToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            Saml2SecurityToken samlToken = token as Saml2SecurityToken;
            if (null == samlToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID1064, token.GetType().ToString()));
            }

            // by default we only check bearer tokens.
            if (samlToken.SecurityKeys.Count != 0)
            {
                return;
            }

            if (Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (Configuration.Caches.TokenReplayCache == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4278));
            }

            if (string.IsNullOrEmpty(samlToken.Assertion.Id.Value))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID1065)));
            }

            StringBuilder stringBuilder = new StringBuilder();
            string key;

            using (HashAlgorithm hashAlgorithm = CryptoHelper.NewSha256HashAlgorithm())
            {
                if (string.IsNullOrEmpty(samlToken.Assertion.Issuer.Value))
                {
                    stringBuilder.AppendFormat("{0}{1}", samlToken.Assertion.Id.Value, tokenTypeIdentifiers[0]);
                }
                else
                {
                    stringBuilder.AppendFormat("{0}{1}{2}", samlToken.Assertion.Id.Value, samlToken.Assertion.Issuer.Value, tokenTypeIdentifiers[0]);
                }

                key = Convert.ToBase64String(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())));
            }

            if (Configuration.Caches.TokenReplayCache.Contains(key))
            {
                string issuer = (samlToken.Assertion.Issuer.Value != null) ? samlToken.Assertion.Issuer.Value : String.Empty;

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenReplayDetectedException(SR.GetString(SR.ID1066, typeof(Saml2SecurityToken).ToString(), samlToken.Assertion.Id.Value, issuer)));
            }
            else
            {
                Configuration.Caches.TokenReplayCache.AddOrUpdate(key, token, DateTimeUtil.Add(this.GetTokenReplayCacheEntryExpirationTime(samlToken), Configuration.MaxClockSkew));
            }
        }
        /// <summary>
        /// Writes a given SecurityToken to a string.
        /// </summary>
        /// <param name="token">SecurityToken to be written out.</param>
        /// <returns>The serialized token.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        public string WriteToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SecurityTokenHandler handler = this[token];

            if (null == handler || !handler.CanWriteToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4010, token.GetType())));
            }

            return(handler.WriteToken(token));
        }
        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();
        }
Exemplo n.º 37
0
 protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.StandardsManagerCannotWriteObject, token.GetType())));
 }
 private X509SecurityToken ValidateX509Token(SecurityToken token)
 {
     X509SecurityToken token2 = token as X509SecurityToken;
     if (token2 == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("TokenProviderReturnedBadToken", new object[] { (token == null) ? "<null>" : token.GetType().ToString() })));
     }
     System.ServiceModel.Security.SecurityUtils.EnsureCertificateCanDoKeyExchange(token2.Certificate);
     return token2;
 }