// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Security.Claims; using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens { /// /// Contains a set of parameters that are used by a when validating a . /// public partial class TokenValidationParameters { private string _authenticationType; private TimeSpan _clockSkew = DefaultClockSkew; private string _nameClaimType = ClaimsIdentity.DefaultNameClaimType; private string _roleClaimType = ClaimsIdentity.DefaultRoleClaimType; private Dictionary _instancePropertyBag; /// /// This is the default value of when creating a . /// The value is "AuthenticationTypes.Federation". /// To change the value, set to a different value. /// public static readonly string DefaultAuthenticationType = "AuthenticationTypes.Federation"; // Note: The change was because 5.x removed the dependency on System.IdentityModel and we used a different string which was a mistake. /// /// Default for the clock skew. /// /// 300 seconds (5 minutes). public static readonly TimeSpan DefaultClockSkew = TimeSpan.FromSeconds(300); // 5 min. /// /// Default for the maximum token size. /// /// 250 KB (kilobytes). public const int DefaultMaximumTokenSizeInBytes = 1024 * 250; /// /// Copy constructor for . /// protected TokenValidationParameters(TokenValidationParameters other) { if (other == null) throw LogHelper.LogExceptionMessage(new ArgumentNullException(nameof(other))); AlgorithmValidator = other.AlgorithmValidator; ActorValidationParameters = other.ActorValidationParameters?.Clone(); AudienceValidator = other.AudienceValidator; _authenticationType = other._authenticationType; ClockSkew = other.ClockSkew; ConfigurationManager = other.ConfigurationManager; CryptoProviderFactory = other.CryptoProviderFactory; DebugId = other.DebugId; IncludeTokenOnFailedValidation = other.IncludeTokenOnFailedValidation; IgnoreTrailingSlashWhenValidatingAudience = other.IgnoreTrailingSlashWhenValidatingAudience; IgnoreCaseWhenValidatingAudience = other.IgnoreCaseWhenValidatingAudience; IssuerSigningKey = other.IssuerSigningKey; IssuerSigningKeyResolver = other.IssuerSigningKeyResolver; IssuerSigningKeyResolverUsingConfiguration = other.IssuerSigningKeyResolverUsingConfiguration; IssuerSigningKeys = other.IssuerSigningKeys is not null ? new List(other.IssuerSigningKeys) : null; IssuerSigningKeyValidator = other.IssuerSigningKeyValidator; IssuerSigningKeyValidatorUsingConfiguration = other.IssuerSigningKeyValidatorUsingConfiguration; IssuerValidator = other.IssuerValidator; IssuerValidatorAsync = other.IssuerValidatorAsync; IssuerValidatorUsingConfiguration = other.IssuerValidatorUsingConfiguration; LifetimeValidator = other.LifetimeValidator; LogTokenId = other.LogTokenId; LogValidationExceptions = other.LogValidationExceptions; NameClaimType = other.NameClaimType; NameClaimTypeRetriever = other.NameClaimTypeRetriever; PropertyBag = other.PropertyBag switch { null => null, Dictionary dictionary => new Dictionary(dictionary, dictionary.Comparer), _ => new Dictionary(other.PropertyBag) }; TryReadJwtClaim = other.TryReadJwtClaim; RefreshBeforeValidation = other.RefreshBeforeValidation; RequireAudience = other.RequireAudience; // CodeQL [SM03926] intentional: Value is copied regardless of whether it is true or false. RequireExpirationTime = other.RequireExpirationTime; RequireSignedTokens = other.RequireSignedTokens; RoleClaimType = other.RoleClaimType; RoleClaimTypeRetriever = other.RoleClaimTypeRetriever; SaveSigninToken = other.SaveSigninToken; SignatureValidator = other.SignatureValidator; SignatureValidatorUsingConfiguration = other.SignatureValidatorUsingConfiguration; TokenDecryptionKey = other.TokenDecryptionKey; TokenDecryptionKeyResolver = other.TokenDecryptionKeyResolver; TokenDecryptionKeys = other.TokenDecryptionKeys is not null ? new List(other.TokenDecryptionKeys) : null; TokenReader = other.TokenReader; TokenReplayCache = other.TokenReplayCache; TokenReplayValidator = other.TokenReplayValidator; TransformBeforeSignatureValidation = other.TransformBeforeSignatureValidation; TryAllDecryptionKeys = other.TryAllDecryptionKeys; TryAllIssuerSigningKeys = other.TryAllIssuerSigningKeys; TypeValidator = other.TypeValidator; ValidateActor = other.ValidateActor; // CodeQL [SM03926] intentional: Value is copied regardless of whether it is true or false. ValidateAudience = other.ValidateAudience; // CodeQL [SM03926] intentional: Value is copied regardless of whether it is true or false. ValidateIssuer = other.ValidateIssuer; ValidateIssuerSigningKey = other.ValidateIssuerSigningKey; // CodeQL [SM03926] intentional: Value is copied regardless of whether it is true or false. ValidateLifetime = other.ValidateLifetime; ValidateSignatureLast = other.ValidateSignatureLast; ValidateTokenReplay = other.ValidateTokenReplay; ValidateWithLKG = other.ValidateWithLKG; ValidAlgorithms = other.ValidAlgorithms is not null ? new List(other.ValidAlgorithms) : null; ValidAudience = other.ValidAudience; ValidAudiences = other.ValidAudiences is not null ? new List(other.ValidAudiences) : null; ValidIssuer = other.ValidIssuer; ValidIssuers = other.ValidIssuers is not null ? new List(other.ValidIssuers) : null; ValidTypes = other.ValidTypes is not null ? new List(other.ValidTypes) : null; ActClaimRetriever = other.ActClaimRetriever; } /// /// Initializes a new instance of the class. /// public TokenValidationParameters() { LogTokenId = true; LogValidationExceptions = true; RequireExpirationTime = true; RequireSignedTokens = true; RequireAudience = true; SaveSigninToken = false; TryAllDecryptionKeys = true; TryAllIssuerSigningKeys = true; ValidateActor = false; ValidateAudience = true; ValidateIssuer = true; ValidateIssuerSigningKey = false; ValidateLifetime = true; ValidateTokenReplay = false; } /// /// Gets or sets . /// public TokenValidationParameters ActorValidationParameters { get; set; } /// /// Gets or sets a delegate used to validate the cryptographic algorithm used. /// /// /// If set, this delegate will validate the cryptographic algorithm used and /// the algorithm will not be checked against . /// public AlgorithmValidator AlgorithmValidator { get; set; } /// /// Gets or sets a delegate that will be used to validate the audience. /// /// /// If set, this delegate will be called to validate the 'audience', instead of default processing. /// This means that no default 'audience' validation will occur. /// Even if is false, this delegate will still be called. /// public AudienceValidator AudienceValidator { get; set; } /// /// Gets or sets the AuthenticationType when creating a . /// /// If 'value' is null or whitespace. public string AuthenticationType { get { return _authenticationType; } set { if (string.IsNullOrWhiteSpace(value)) { throw LogHelper.LogExceptionMessage(new ArgumentNullException("AuthenticationType")); } _authenticationType = value; } } /// /// Gets or sets the clock skew to apply when validating a time. /// /// If 'value' is less than 0. /// The default is 300 seconds (5 minutes). [DefaultValue(300)] public TimeSpan ClockSkew { get { return _clockSkew; } set { if (value < TimeSpan.Zero) throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogHelper.FormatInvariant(LogMessages.IDX10100, LogHelper.MarkAsNonPII(value)))); _clockSkew = value; } } /// /// Returns a new instance of with values copied from this object. /// /// A new object copied from this object. /// This is a deep Clone. public virtual TokenValidationParameters Clone() { return new TokenValidationParameters(this) { IsClone = true }; } /// /// Creates a using: /// /// 'NameClaimType': If NameClaimTypeRetriever is set, call delegate, else call NameClaimType. If the result is a null or empty string, use . /// 'RoleClaimType': If RoleClaimTypeRetriever is set, call delegate, else call RoleClaimType. If the result is a null or empty string, use . /// /// A with Authentication, NameClaimType and RoleClaimType set. public virtual ClaimsIdentity CreateClaimsIdentity(SecurityToken securityToken, string issuer) { string nameClaimType = null; if (NameClaimTypeRetriever != null) { nameClaimType = NameClaimTypeRetriever(securityToken, issuer); } else { nameClaimType = NameClaimType; } string roleClaimType = null; if (RoleClaimTypeRetriever != null) { roleClaimType = RoleClaimTypeRetriever(securityToken, issuer); } else { roleClaimType = RoleClaimType; } if (LogHelper.IsEnabled(EventLogLevel.Informational)) LogHelper.LogInformation(LogMessages.IDX10245, securityToken); return ClaimsIdentityFactory.Create( authenticationType: AuthenticationType ?? DefaultAuthenticationType, nameType: nameClaimType ?? ClaimsIdentity.DefaultNameClaimType, roleType: roleClaimType ?? ClaimsIdentity.DefaultRoleClaimType, securityToken); } /// /// If set, this property will be used to obtain the issuer and signing keys associated with the metadata endpoint of . /// The obtained issuer and signing keys will then be used along with those present on the TokenValidationParameters for validation of the incoming token. /// public BaseConfigurationManager ConfigurationManager { get; set; } /// /// Users can override the default with this property. This factory will be used for creating signature providers. /// public CryptoProviderFactory CryptoProviderFactory { get; set; } /// /// Gets or sets a string that helps with setting breakpoints when debugging. /// public string DebugId { get; set; } /// /// Gets or sets a boolean that controls if a '/' is significant at the end of the audience. /// The default is true. /// [DefaultValue(true)] public bool IgnoreTrailingSlashWhenValidatingAudience { get; set; } = true; /// /// Gets or sets a boolean that controls if case is ignored when validating the audience. /// The default is false, meaning audience comparison is case-sensitive (ordinal). /// [DefaultValue(false)] public bool IgnoreCaseWhenValidatingAudience { get; set; } /// /// Gets or sets the flag that indicates whether to include the when the validation fails. /// public bool IncludeTokenOnFailedValidation { get; set; } /// /// Gets or sets a delegate for validating the that signed the token. /// /// /// If set, this delegate will be called to validate the that signed the token, instead of default processing. /// This means that no default validation will occur. /// Even if is false, this delegate will still be called. /// If both and are set, IssuerSigningKeyResolverUsingConfiguration takes /// priority. /// public IssuerSigningKeyValidator IssuerSigningKeyValidator { get; set; } /// /// Gets or sets a delegate for validating the that signed the token. /// /// /// If set, this delegate will be called to validate the that signed the token, instead of default processing. /// This means that no default validation will occur. /// Even if is false, this delegate will still be called. /// This delegate should be used if properties from the configuration retrieved from the authority are necessary to validate the /// issuer signing key. /// If both and are set, IssuerSigningKeyValidatorUsingConfiguration takes /// priority. /// public IssuerSigningKeyValidatorUsingConfiguration IssuerSigningKeyValidatorUsingConfiguration { get; set; } /// /// Gets a that is unique to this instance. /// Calling will result in a new instance of this IDictionary. /// public IDictionary InstancePropertyBag => _instancePropertyBag ??= new Dictionary(); /// /// Gets a value indicating if was called to obtain this instance. /// public bool IsClone { get; protected set; } /// /// Gets or sets the that is to be used for signature validation. /// public SecurityKey IssuerSigningKey { get; set; } /// /// Gets or sets a delegate that will be called to retrieve a used for signature validation. /// /// /// This will be used to check the signature. This can be helpful when the does not contain a key identifier. /// If both and are set, IssuerSigningKeyResolverUsingConfiguration takes /// priority. /// public IssuerSigningKeyResolver IssuerSigningKeyResolver { get; set; } /// /// Gets or sets a delegate that will be called to retrieve a used for signature validation using the /// and . /// /// /// This will be used to check the signature. This can be helpful when the does not contain a key identifier. /// This delegate should be used if properties from the configuration retrieved from the authority are necessary to resolve the /// issuer signing key. /// If both and are set, IssuerSigningKeyResolverUsingConfiguration takes /// priority. /// public IssuerSigningKeyResolverUsingConfiguration IssuerSigningKeyResolverUsingConfiguration { get; set; } /// /// Gets or sets an used for signature validation. /// public IEnumerable IssuerSigningKeys { get; set; } /// /// Gets or sets a delegate that will be used to validate the issuer of the token. /// /// /// If set, this delegate will be called to validate the 'issuer' of the token, instead of default processing. /// This means that no default 'issuer' validation will occur. /// Even if is false, this delegate will still be called. /// If both and are set, IssuerValidatorUsingConfiguration takes /// priority. /// public IssuerValidator IssuerValidator { get; set; } /// /// Gets or sets a delegate that will be used to validate the issuer of the token. /// /// /// If set, this delegate will be called to validate the 'issuer' of the token, instead of default processing. /// This means that no default 'issuer' validation will occur. /// Even if is false, this delegate will still be called. /// IssuerValidatorAsync takes precedence over and . /// internal IssuerValidatorAsync IssuerValidatorAsync { get; set; } /// /// Gets or sets a delegate that will be used to validate the issuer of the token. /// /// /// If set, this delegate will be called to validate the 'issuer' of the token, instead of default processing. /// This means that no default 'issuer' validation will occur. /// Even if is false, this delegate will still be called. /// This delegate should be used if properties from the configuration retrieved from the authority are necessary to validate the issuer. /// If both and are set, IssuerValidatorUsingConfiguration takes /// priority. /// public IssuerValidatorUsingConfiguration IssuerValidatorUsingConfiguration { get; set; } /// /// Gets or sets a delegate that will be called to transform a token to a supported format before validation. /// public TransformBeforeSignatureValidation TransformBeforeSignatureValidation { get; set; } /// /// Gets or sets a delegate that will be used to validate the lifetime of the token /// /// /// If set, this delegate will be called to validate the lifetime of the token, instead of default processing. /// This means that no default lifetime validation will occur. /// Even if is false, this delegate will still be called. /// public LifetimeValidator LifetimeValidator { get; set; } /// /// Gets or sets a that will decide if the token identifier claim needs to be logged. /// Default value is true. /// [DefaultValue(true)] public bool LogTokenId { get; set; } /// /// Gets or sets a that will decide if validation failure needs to be logged as an error. /// Default value is true for backward compatibility of the behavior. /// If set to false, validation failures are logged as Information and then thrown. /// [DefaultValue(true)] public bool LogValidationExceptions { get; set; } /// /// Gets or sets a that defines the . /// /// /// Controls the value returns. It will return the first where the equals . /// The default is . /// public string NameClaimType { get { return _nameClaimType; } set { if (string.IsNullOrWhiteSpace(value)) throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogMessages.IDX10102)); _nameClaimType = value; } } /// /// Gets or sets a delegate that will be called to set the property after validating a token. /// /// /// The function will be passed: /// The that is being validated. /// The issuer associated with the token. /// Returns the value that will set the property . /// public Func NameClaimTypeRetriever { get; set; } /// /// Gets or sets the that contains a collection of custom key/value pairs. This allows addition of parameters that could be used in custom token validation scenarios. /// public IDictionary PropertyBag { get; set; } /// /// Gets or sets the delegate that will be called when reading JSON Web Token header and payload claims. /// public TryReadJwtClaim TryReadJwtClaim { get; set; } /// /// Gets or sets a boolean to control if configuration required to be refreshed before token validation. /// /// /// The default is false. /// [DefaultValue(false)] public bool RefreshBeforeValidation { get; set; } /// /// Gets or sets a value indicating whether SAML or JWT tokens must have at least one AudienceRestriction. /// The default is true. /// /// /// If set to false and the Audience is null, Audience validation will be skipped. /// If set to false and the Audience is not null, the Audience will still be validated. /// [DefaultValue(true)] public bool RequireAudience { get; set; } /// /// Gets or sets a value indicating whether tokens must have an 'expiration' value. /// The default is true. /// [DefaultValue(true)] public bool RequireExpirationTime { get; set; } /// /// Gets or sets a value indicating whether a can be considered valid if not signed. /// The default is true. /// [DefaultValue(true)] public bool RequireSignedTokens { get; set; } /// /// Gets or sets the that defines the . /// /// /// Controls the results of . /// Each where == will be checked for a match against the 'string' passed to . /// The default is . /// public string RoleClaimType { get { return _roleClaimType; } set { if (string.IsNullOrWhiteSpace(value)) throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogMessages.IDX10103)); _roleClaimType = value; } } /// /// Gets or sets a delegate that will be called to set the property after validating a token. /// /// /// The function will be passed: /// The that is being validated. /// The issuer associated with the token. /// Returns the value that will set the property . /// public Func RoleClaimTypeRetriever { get; set; } /// /// Gets or sets a boolean to control if the original token should be saved after the security token is validated. /// /// The runtime will consult this value and save the original token that was validated. /// The default is false. /// [DefaultValue(false)] public bool SaveSigninToken { get; set; } /// /// Gets or sets a delegate that will be used to validate the signature of the token. /// /// /// If set, this delegate will be called to validate the signature of the token, instead of default processing. /// public SignatureValidator SignatureValidator { get; set; } /// /// Gets or sets a delegate that will be used to validate the signature of the token using the and /// the . /// /// /// If set, this delegate will be called to validate the signature of the token, instead of default processing. /// public SignatureValidatorUsingConfiguration SignatureValidatorUsingConfiguration { get; set; } /// /// Gets or sets the time provider. /// internal TimeProvider TimeProvider { get; set; } = TimeProvider.System; /// /// Gets or sets the that is to be used for decryption. /// /// /// This will only be used if its matches the 'kid' parameter in the token. /// public SecurityKey TokenDecryptionKey { get; set; } /// /// Gets or sets a delegate that will be called to retrieve a used for decryption. /// /// /// This will be used to decrypt the token. This can be helpful when the does not contain a key identifier. /// public TokenDecryptionKeyResolver TokenDecryptionKeyResolver { get; set; } /// /// Gets or sets the that is to be used for decrypting inbound tokens. /// /// /// The decryption keys in this collection will only be used if their matches the 'kid' parameter in the token. /// public IEnumerable TokenDecryptionKeys { get; set; } /// /// Gets or sets a delegate that will be used to read the token. /// /// /// If set, this delegate will be called to read the token instead of default processing. /// public TokenReader TokenReader { get; set; } /// /// Gets or set the that store tokens that can be checked to help detect token replay. /// /// If set, then tokens must have an expiration time or the runtime will fault. public ITokenReplayCache TokenReplayCache { get; set; } /// /// Gets or sets a delegate that will be used to validate the token replay of the token /// /// /// If set, this delegate will be called to validate the token replay of the token, instead of default processing. /// This means no default token replay validation will occur. /// Even if is false, this delegate will still be called. /// public TokenReplayValidator TokenReplayValidator { get; set; } /// /// Gets or sets a value indicating whether all should be tried during token decryption when a key is not matched to token 'kid' or if token 'kid' is empty. /// The default is true. /// [DefaultValue(true)] public bool TryAllDecryptionKeys { get; set; } /// /// Gets or sets a value indicating whether all should be tried during signature validation when a key is not matched to token 'kid' or if token 'kid' is empty. /// The default is true. /// [DefaultValue(true)] public bool TryAllIssuerSigningKeys { get; set; } /// /// Gets or sets a delegate that will be used to validate the type of the token. /// If the token type cannot be validated, an exception MUST be thrown by the delegate. /// Note: the 'type' parameter may be null if it couldn't be extracted from its usual location. /// Implementations that need to resolve it from a different location can use the 'token' parameter. /// /// /// If set, this delegate will be called to validate the 'type' of the token, instead of default processing. /// This means that no default 'type' validation will occur. /// public TypeValidator TypeValidator { get; set; } /// /// Gets or sets a value indicating if an actor token is detected, whether it should be validated. /// The default is false. /// [DefaultValue(false)] public bool ValidateActor { get; set; } /// /// Gets or sets a boolean to control if the audience will be validated during token validation. /// /// Validation of the audience, mitigates forwarding attacks. For example, a site that receives a token, could not replay it to another site. /// A forwarded token would contain the audience of the original site. /// This boolean only applies to default audience validation. If is set, it will be called regardless of whether this /// property is true or false. /// The default is true. /// [DefaultValue(true)] public bool ValidateAudience { get; set; } /// /// Gets or sets a boolean to control if the issuer will be validated during token validation. /// /// /// Validation of the issuer mitigates forwarding attacks that can occur when an /// IdentityProvider represents multiple tenants and signs tokens with the same keys. /// It is possible that a token issued for the same audience could be from a different tenant. For example an application could accept users from /// contoso.onmicrosoft.com but not fabrikam.onmicrosoft.com, both valid tenants. An application that accepts tokens from fabrikam could forward them /// to the application that accepts tokens for contoso. /// This boolean only applies to default issuer validation. If is set, it will be called regardless of whether this /// property is true or false. /// The default is true. /// [DefaultValue(true)] public bool ValidateIssuer { get; set; } /// /// Gets or sets a boolean to control if the LKG configuration will be used for token validation. /// /// /// The default is false. /// [DefaultValue(false)] public bool ValidateWithLKG { get; set; } /// /// Gets or sets a boolean that controls if validation of the that signed the securityToken is called. /// /// It is possible for tokens to contain the public key needed to check the signature. For example, X509Data can be hydrated into an X509Certificate, /// which can be used to validate the signature. In these cases it is important to validate the SigningKey that was used to validate the signature. /// This boolean only applies to default signing key validation. If is set, it will be called regardless of whether this /// property is true or false. /// The default is false. /// [DefaultValue(false)] public bool ValidateIssuerSigningKey { get; set; } /// /// Gets or sets a boolean to control if the lifetime will be validated during token validation. /// /// /// This boolean only applies to default lifetime validation. If is set, it will be called regardless of whether this /// property is true or false. /// The default is true. /// [DefaultValue(true)] public bool ValidateLifetime { get; set; } /// /// Gets or sets a boolean that controls the validation order of the payload and signature during token validation. /// /// If is set to true, it will validate payload ahead of signature. /// The default is false. /// [DefaultValue(false)] public bool ValidateSignatureLast { get; set; } /// /// Gets or sets a boolean to control if the token replay will be validated during token validation. /// /// /// This boolean only applies to default token replay validation. If is set, it will be called regardless of whether this /// property is true or false. /// The default is false. /// [DefaultValue(false)] public bool ValidateTokenReplay { get; set; } /// /// Gets or sets the valid algorithms for cryptographic operations. /// /// /// If set to a non-empty collection, only the algorithms listed will be considered valid. /// The default is null. /// public IEnumerable ValidAlgorithms { get; set; } /// /// Gets or sets a string that represents a valid audience that will be used to check against the token's audience. /// The default is null. /// public string ValidAudience { get; set; } /// /// Gets or sets the that contains valid audiences that will be used to check against the token's audience. /// The default is null. /// public IEnumerable ValidAudiences { get; set; } /// /// Gets or sets a that represents a valid issuer that will be used to check against the token's issuer. /// The default is null. /// public string ValidIssuer { get; set; } /// /// Gets or sets the that contains valid issuers that will be used to check against the token's issuer. /// The default is null. /// public IEnumerable ValidIssuers { get; set; } /// /// Gets or sets the that contains valid types that will be used to check against the JWT header's 'typ' claim. /// If this property is not set, the 'typ' header claim will not be validated and all types will be accepted. /// In the case of a JWE, this property will ONLY apply to the inner token header. /// The default is null. /// public IEnumerable ValidTypes { get; set; } /// /// Gets or sets the delegate that will be used to convert the 'act' claim JSON into a ClaimsIdentity. /// This delegate is invoked during token validation when an actor claim is encountered in a token. /// The delegate receives a representing the actor claim /// and should return a that represents the actor. /// /// /// When this delegate is provided, it replaces the default actor claim processing logic. /// This is useful for custom actor claim formats or when special processing is needed for the actor claims. /// The delegate can also handle nested actors by recursively creating actor identities and setting the Actor property. /// /// validationParameters.ActClaimRetriever = (JsonElement element,TokenValidationParameters tokenValidationParameters) => { /// var identity = new ClaimsIdentity("CustomActor"); /// // Extract claims from the JsonElement /// if (element.TryGetProperty("sub", out var sub)) /// identity.AddClaim(new Claim("sub", sub.GetString())); /// return identity; /// }; /// /// public ActClaimRetriever ActClaimRetriever { get; set; } } }