Class JwtConsumerBuilder
Use the JwtConsumerBuilder to create the appropriate JwtConsumer for your JWT processing needs.
The specific validation requirements for a JWT are context dependent, however, it typically advisable to require a (reasonable) expiration time, a trusted issuer, and and audience that identifies your system as the intended recipient. For example, aJwtConsumer might be set up and used like this:
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime() // the JWT must have an expiration time
.setMaxFutureValidityInMinutes(300) // but the expiration time can't be too crazy
.setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by
.setExpectedAudience("Audience") // to whom the JWT is intended for
.setVerificationKey(publicKey) // verify the signature with the public key
.build(); // create the JwtConsumer instance
try
{
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
System.out.println("JWT validation succeeded! " + jwtClaims);
}
catch (InvalidJwtException e)
{
// InvalidJwtException will be thrown, if the JWT failed processing or validation in anyway.
// Hopefully with meaningful explanations(s) about what went wrong.
System.out.println("Invalid JWT! " + e);
}
JwtConsumer instances created from this are thread safe and reusable (as long as any custom Validators or Customizers used are also thread safe).
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a new JwtConsumerBuilder, which is set up by default to build a JwtConsumer that requires a signature and will validate the core JWT claims when they are present. -
Method Summary
Modifier and TypeMethodDescriptionbuild()Create the JwtConsumer with the options provided to the builder.registerValidator(ErrorCodeValidator validator) Custom ErrorCodeValidator implementations, which will be invoked when theJwtConsumeris validating the JWT claims.registerValidator(Validator validator) Custom Validator implementations, which will be invoked when theJwtConsumeris validating the JWT claims.setAllowedClockSkewInSeconds(int secondsOfAllowedClockSkew) Set the amount of clock skew to allow for when validate the expiration time, issued at time, and not before time claims.setDecryptionKey(Key decryptionKey) Set the key to be used for JWE decryption.setDecryptionKeyResolver(DecryptionKeyResolver decryptionKeyResolver) Set the DecryptionKeyResolver to use to select the key for JWE decryption.Because integrity protection is needed in most usages of JWT, a signature on the JWT is required by default.According to section 5.2 of the JWT spec, when nested signing or encryption is employed with a JWT, the "cty" header parameter has to be present and have a value of "JWT" to indicate that a nested JWT is the payload of the outer JWT.Require that the JWT be encrypted, which is not required by default.Require that the JWT have some integrity protection, either a signature/MAC JWS or a JWE using a symmetric key management algorithm.setEvaluationTime(NumericDate evaluationTime) Set the time used to validate the expiration time, issued at time, and not before time claims.setExpectedAudience(boolean requireAudienceClaim, String... audience) Set the audience value(s) to use when validating the audience ("aud") claim of a JWT.setExpectedAudience(String... audience) Set the audience value(s) to use when validating the audience ("aud") claim of a JWT and require that an audience claim be present.setExpectedIssuer(boolean requireIssuer, String expectedIssuer) Indicates whether or not the issuer ("iss") claim is required and optionally what the expected value is.setExpectedIssuer(String expectedIssuer) Indicates the expected value of the issuer ("iss") claim and that the claim is required.setExpectedIssuers(boolean requireIssuer, String... expectedIssuers) Indicates whether or not the issuer ("iss") claim is required and optionally what the expected values can be.setExpectedSubject(String subject) Require that a subject ("sub") claim be present in the JWT and that its value match that of the provided subject.setExpectedType(boolean requireType, String expectedType) Facilities explicit JWT typing by setting the expected media type value of the "typ" header of the innermost JWT including prepending "application/" to any "typ" value not containing a '/' as defined in Section 4.1.9 of RFC 7515.setIssuedAtRestrictions(int allowedSecondsInTheFuture, int allowedSecondsInThePast) Places restrictions on how far from the time of evaluation the value of an issued at time ("iat") claim can be while still accepting the token as valid.setJweAlgorithmConstraints(AlgorithmConstraints constraints) Set the JWE algorithm constraints to be applied to key management when processing the JWT.setJweAlgorithmConstraints(AlgorithmConstraints.ConstraintType type, String... algorithms) Set the JWE algorithm constraints to be applied to key management when processing the JWT.Set the JWE algorithm constraints to be applied to content encryption when processing the JWT.setJweContentEncryptionAlgorithmConstraints(AlgorithmConstraints.ConstraintType type, String... algorithms) Set the JWE algorithm constraints to be applied to content encryption when processing the JWT.setJweCustomizer(JweCustomizer jweCustomizer) Set a callback JweCustomizer that provides a hook to call arbitrary methods on the/any JsonWebEncryption prior to the JwsConsumer using it for decryption.setJweProviderContext(ProviderContext jweProviderContext) Sets theProviderContextfor any JWE operations to be done by the JwtConsumer being built.setJwsAlgorithmConstraints(AlgorithmConstraints constraints) Set the JWS algorithm constraints to be applied when processing the JWT.setJwsAlgorithmConstraints(AlgorithmConstraints.ConstraintType type, String... algorithms) Set the JWS algorithm constraints to be applied when processing the JWT.setJwsCustomizer(JwsCustomizer jwsCustomizer) Set a callback JwsCustomizer that provides a hook to call arbitrary methods on the/any JsonWebSignature prior to the JwsConsumer using it to verify the signature.setJwsProviderContext(ProviderContext jwsProviderContext) Sets theProviderContextfor any JWS operations to be done by the JwtConsumer being built.setMaxFutureValidityInMinutes(int maxFutureValidityInMinutes) Set maximum on how far in the future the "exp" claim can be.Bypass the strict checks on the decryption key.Bypass the strict checks on the verification key.Require that the JWT contain an expiration time ("exp") claim.Require that the JWT contain an issued at time ("iat") claim.Require that a JWT ID ("jti") claim be present in the JWT.Require that the JWT contain an not before ("nbf") claim.Require that a subject ("sub") claim be present in the JWT.Skip all the default claim validation but not those provided viaregisterValidator(Validator).Skip all claims validation.Skip the default audience validation.Skip signature verification.Indicates that the JwtConsumer will not call the VerificationKeyResolver for a JWS using the 'none' algorithm.setVerificationKey(Key verificationKey) Set the key to be used for JWS signature/MAC verification.setVerificationKeyResolver(VerificationKeyResolver verificationKeyResolver) Set the VerificationKeyResolver to use to select the key for JWS signature/MAC verification.
-
Constructor Details
-
JwtConsumerBuilder
public JwtConsumerBuilder()Creates a new JwtConsumerBuilder, which is set up by default to build a JwtConsumer that requires a signature and will validate the core JWT claims when they are present. The various methods on the builder should be used to customize the JwtConsumer's behavior as appropriate.
-
-
Method Details
-
setEnableRequireEncryption
Require that the JWT be encrypted, which is not required by default.- Returns:
- the same JwtConsumerBuilder
-
setEnableRequireIntegrity
Require that the JWT have some integrity protection, either a signature/MAC JWS or a JWE using a symmetric key management algorithm.- Returns:
- the same JwtConsumerBuilder
-
setDisableRequireSignature
Because integrity protection is needed in most usages of JWT, a signature on the JWT is required by default. Calling this turns that requirement off. It may be necessary, for example, when integrity is ensured though other means like a JWE using a symmetric key management algorithm. Use this in conjunction withsetEnableRequireIntegrity()for that case.- Returns:
- the same JwtConsumerBuilder
-
setEnableLiberalContentTypeHandling
According to section 5.2 of the JWT spec, when nested signing or encryption is employed with a JWT, the "cty" header parameter has to be present and have a value of "JWT" to indicate that a nested JWT is the payload of the outer JWT.
Not all JWTs follow that requirement of the spec and this provides a work around for consuming non-compliant JWTs. Calling this method tells the JwtConsumer to be a bit more liberal in processing and make a best effort when the "cty" header isn’t present and the payload doesn't parse as JSON but can be parsed into a JOSE object.
- Returns:
- the same JwtConsumerBuilder
-
setSkipSignatureVerification
Skip signature verification.
This might be useful in cases where you don't have enough information to set up a validating JWT consumer without cracking open the JWT first. For example, in some contexts you might not know who issued the token without looking at the "iss" claim inside the JWT. In such a case two JwtConsumers cab be used in a "two-pass" validation of sorts - the first JwtConsumer parses the JWT but doesn't validate the signature or claims due to the use of methods like this one and the second JwtConsumers does the actual validation.- Returns:
- the same JwtConsumerBuilder
-
setSkipAllValidators
Skip all claims validation.
This might be useful in cases where you don't have enough information to set up a validating JWT consumer without cracking open the JWT first. For example, in some contexts you might not know who issued the token without looking at the "iss" claim inside the JWT. In such a case two JwtConsumers cab be used in a "two-pass" validation of sorts - the first JwtConsumer parses the JWT but doesn't validate the signature or claims due to the use of methods like this one and the second JwtConsumers does the actual validation.- Returns:
- the same JwtConsumerBuilder
-
setSkipAllDefaultValidators
Skip all the default claim validation but not those provided viaregisterValidator(Validator).- Returns:
- the same JwtConsumerBuilder
-
setJwsAlgorithmConstraints
Set the JWS algorithm constraints to be applied when processing the JWT.- Parameters:
constraints- the AlgorithmConstraints to use for JWS processing- Returns:
- the same JwtConsumerBuilder
-
setJweAlgorithmConstraints
Set the JWE algorithm constraints to be applied to key management when processing the JWT.- Parameters:
constraints- the AlgorithmConstraints to use for JWE key management algorithm processing- Returns:
- the same JwtConsumerBuilder
-
setJweContentEncryptionAlgorithmConstraints
public JwtConsumerBuilder setJweContentEncryptionAlgorithmConstraints(AlgorithmConstraints constraints) Set the JWE algorithm constraints to be applied to content encryption when processing the JWT.- Parameters:
constraints- the AlgorithmConstraints to use for JWE content encryption processing- Returns:
- the same JwtConsumerBuilder
-
setJwsAlgorithmConstraints
public JwtConsumerBuilder setJwsAlgorithmConstraints(AlgorithmConstraints.ConstraintType type, String... algorithms) Set the JWS algorithm constraints to be applied when processing the JWT.- Parameters:
type- the type of constraint i.e. block or permitalgorithms- the algorithms to be allowed or disallowed depending on the constraint type- Returns:
- the same JwtConsumerBuilder
-
setJweAlgorithmConstraints
public JwtConsumerBuilder setJweAlgorithmConstraints(AlgorithmConstraints.ConstraintType type, String... algorithms) Set the JWE algorithm constraints to be applied to key management when processing the JWT.- Parameters:
type- the type of constraint i.e. block or permitalgorithms- the algorithms to be allowed or disallowed depending on the constraint type- Returns:
- the same JwtConsumerBuilder
-
setJweContentEncryptionAlgorithmConstraints
public JwtConsumerBuilder setJweContentEncryptionAlgorithmConstraints(AlgorithmConstraints.ConstraintType type, String... algorithms) Set the JWE algorithm constraints to be applied to content encryption when processing the JWT.- Parameters:
type- the type of constraint i.e. block or permitalgorithms- the algorithms to be allowed or disallowed depending on the constraint type- Returns:
- the same JwtConsumerBuilder
-
setVerificationKey
Set the key to be used for JWS signature/MAC verification.- Parameters:
verificationKey- the verification key.- Returns:
- the same JwtConsumerBuilder
-
setVerificationKeyResolver
public JwtConsumerBuilder setVerificationKeyResolver(VerificationKeyResolver verificationKeyResolver) Set the VerificationKeyResolver to use to select the key for JWS signature/MAC verification. A VerificationKeyResolver enables a verification key to be chosen dynamically based on more information, like the JWS headers, about the message being processed.- Parameters:
verificationKeyResolver- the VerificationKeyResolver- Returns:
- the same JwtConsumerBuilder
- See Also:
-
setSkipVerificationKeyResolutionOnNone
Indicates that the JwtConsumer will not call the VerificationKeyResolver for a JWS using the 'none' algorithm.- Returns:
- the same JwtConsumerBuilder
-
setDecryptionKey
Set the key to be used for JWE decryption.- Parameters:
decryptionKey- the decryption key.- Returns:
- the same JwtConsumerBuilder
-
setDecryptionKeyResolver
Set the DecryptionKeyResolver to use to select the key for JWE decryption. A DecryptionKeyResolver enables a decryption key to be chosen dynamically based on more information, like the JWE headers, about the message being processed.- Parameters:
decryptionKeyResolver- the DecryptionKeyResolver- Returns:
- the same JwtConsumerBuilder
- See Also:
-
setExpectedAudience
Set the audience value(s) to use when validating the audience ("aud") claim of a JWT and require that an audience claim be present. Audience validation will succeed, if any one of the provided values is equal to any one of the values of the "aud" claim in the JWT.
From Section 4.1.3 of RFC 7519: The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.
Equivalent to calling
setExpectedAudience(boolean, String...)withtrueas the first argument.- Parameters:
audience- the audience value(s) that identify valid recipient(s) of a JWT- Returns:
- the same JwtConsumerBuilder
-
setExpectedAudience
Set the audience value(s) to use when validating the audience ("aud") claim of a JWT. Audience validation will succeed, if any one of the provided values is equal to any one of the values of the "aud" claim in the JWT.
If present, the audience claim will always be validated (unless explicitly disabled). The
requireAudienceClaimparameter can be used to indicate whether or not the presence of the audience claim is required. In most casesrequireAudienceClaimshould betrue.From Section 4.1.3 of RFC 7519: The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.
- Parameters:
requireAudienceClaim- true, if an audience claim has to be present for validation to succeed. false, otherwiseaudience- the audience value(s) that identify valid recipient(s) of a JWT- Returns:
- the same JwtConsumerBuilder
-
setSkipDefaultAudienceValidation
Skip the default audience validation.- Returns:
- the same JwtConsumerBuilder
-
setExpectedIssuers
Indicates whether or not the issuer ("iss") claim is required and optionally what the expected values can be.- Parameters:
requireIssuer- true if issuer claim is required, false otherwiseexpectedIssuers- the values, one of which the issuer claim must match to pass validation,nullmeans that any value is acceptable- Returns:
- the same JwtConsumerBuilder
-
setExpectedIssuer
Indicates whether or not the issuer ("iss") claim is required and optionally what the expected value is.- Parameters:
requireIssuer- true if issuer is required, false otherwiseexpectedIssuer- the value that the issuer claim must have to pass validation,nullmeans that any value is acceptable- Returns:
- the same JwtConsumerBuilder
-
setExpectedIssuer
Indicates the expected value of the issuer ("iss") claim and that the claim is required. Equivalent to callingsetExpectedIssuer(boolean, String)withtrueas the first argument.- Parameters:
expectedIssuer- the value that the issuer claim must have to pass validation,nullmeans that any value is acceptable- Returns:
- the same JwtConsumerBuilder
-
setRequireSubject
Require that a subject ("sub") claim be present in the JWT.- Returns:
- the same JwtConsumerBuilder
-
setExpectedSubject
Require that a subject ("sub") claim be present in the JWT and that its value match that of the provided subject. The subject ("sub") claim is defined in Section 4.1.2 of RFC 7519.- Parameters:
subject- the required value of the subject claim.- Returns:
- the same JwtConsumerBuilder
-
setRequireJwtId
Require that a JWT ID ("jti") claim be present in the JWT.- Returns:
- the same JwtConsumerBuilder
-
setRequireExpirationTime
Require that the JWT contain an expiration time ("exp") claim. The expiration time is always checked when present (unless explicitly disabled) but calling this method strengthens the requirement such that a JWT without an expiration time will not pass validation.- Returns:
- the same JwtConsumerBuilder
-
setRequireIssuedAt
Require that the JWT contain an issued at time ("iat") claim.- Returns:
- the same JwtConsumerBuilder
-
setIssuedAtRestrictions
public JwtConsumerBuilder setIssuedAtRestrictions(int allowedSecondsInTheFuture, int allowedSecondsInThePast) Places restrictions on how far from the time of evaluation the value of an issued at time ("iat") claim can be while still accepting the token as valid. Also usesetRequireIssuedAt()to require that an "iat" claim be present.- Parameters:
allowedSecondsInTheFuture- how many seconds ahead of the current evaluation time the value of the "iat" claim can beallowedSecondsInThePast- how many seconds ago the value of the "iat" claim can be- Returns:
- the same JwtConsumerBuilder
-
setRequireNotBefore
Require that the JWT contain an not before ("nbf") claim.- Returns:
- the same JwtConsumerBuilder
-
setEvaluationTime
Set the time used to validate the expiration time, issued at time, and not before time claims. If not set (or null), the current time will be used to validate the date claims.- Parameters:
evaluationTime- the time with respect to which to validate the date claims.- Returns:
- the same JwtConsumerBuilder
-
setAllowedClockSkewInSeconds
Set the amount of clock skew to allow for when validate the expiration time, issued at time, and not before time claims.- Parameters:
secondsOfAllowedClockSkew- the number of seconds of leniency in date comparisons- Returns:
- the same JwtConsumerBuilder
-
setMaxFutureValidityInMinutes
Set maximum on how far in the future the "exp" claim can be.- Parameters:
maxFutureValidityInMinutes- how far is too far (in minutes)- Returns:
- the same JwtConsumerBuilder
-
setRelaxVerificationKeyValidation
Bypass the strict checks on the verification key. This might be needed, for example, if the JWT issuer is using 1024 bit RSA keys or HMAC secrets that are too small (smaller than the size of the hash output).- Returns:
- the same JwtConsumerBuilder
-
setRelaxDecryptionKeyValidation
Bypass the strict checks on the decryption key.- Returns:
- the same JwtConsumerBuilder
-
registerValidator
Custom Validator implementations, which will be invoked when theJwtConsumeris validating the JWT claims.- Parameters:
validator- the validator- Returns:
- the same JwtConsumerBuilder
-
registerValidator
Custom ErrorCodeValidator implementations, which will be invoked when theJwtConsumeris validating the JWT claims. Error codes can be used for programmatic access to specific reasons for JWT invalidity by usingInvalidJwtException.hasErrorCode(int).- Parameters:
validator- the validator- Returns:
- the same JwtConsumerBuilder
-
setJwsCustomizer
Set a callback JwsCustomizer that provides a hook to call arbitrary methods on the/any JsonWebSignature prior to the JwsConsumer using it to verify the signature. This might be used, for example, to allow for critical ("crit") headers vaiJsonWebStructure.setKnownCriticalHeaders(String...)that the caller knows how to handle and needs to tell the JwsConsumer to allow them.- Parameters:
jwsCustomizer- the JwsCustomizer implementation- Returns:
- the same JwtConsumerBuilder
-
setJweCustomizer
Set a callback JweCustomizer that provides a hook to call arbitrary methods on the/any JsonWebEncryption prior to the JwsConsumer using it for decryption. This might be used, for example, to allow for critical ("crit") headers vaiJsonWebStructure.setKnownCriticalHeaders(String...)that the caller knows how to handle and needs to tell the JwsConsumer to allow them.- Parameters:
jweCustomizer- the JweCustomizer implementation- Returns:
- the same JwtConsumerBuilder
-
setJwsProviderContext
Sets theProviderContextfor any JWS operations to be done by the JwtConsumer being built. This allows for a particular Java Cryptography Architecture provider to be indicated by name to be used for signature/MAC verification operations.- Parameters:
jwsProviderContext- the ProviderContext object indicating the Java Cryptography Architecture provider to be used for JWS signature/MAC verification operations when consuming a JWT.- Returns:
- the same JwtConsumerBuilder
-
setJweProviderContext
Sets theProviderContextfor any JWE operations to be done by the JwtConsumer being built. This allows for a particular Java Cryptography Architecture provider to be indicated by name to be used for decryption and related operations.- Parameters:
jweProviderContext- the ProviderContext object indicating the Java Cryptography Architecture provider to be used for decryption and related operations operations when consuming a JWT.- Returns:
- the same JwtConsumerBuilder
-
setExpectedType
Facilities explicit JWT typing by setting the expected media type value of the "typ" header of the innermost JWT including prepending "application/" to any "typ" value not containing a '/' as defined in Section 4.1.9 of RFC 7515.- Parameters:
requireType- true if the type header is required, false otherwiseexpectedType- the expected value of the "typ" header- Returns:
- the same JwtConsumerBuilder
-
build
Create the JwtConsumer with the options provided to the builder.- Returns:
- the JwtConsumer
-