JWTValidator
Introduction
Since JWT.verify
can only validate the signature of a JWT token, other payload field validations can be done using JWTValidator
.
Usage
Algorithm Validation
Algorithm validation includes two aspects:
- Verifying that the algorithm ID in the header matches the provided algorithm ID.
- Calling
JWT.verify
to validate if the token is correct.
// Create a JWT token
final String token = JWT.create()
.setNotBefore(DateUtil.date())
.setKey("123456".getBytes())
.sign();
// Validate the algorithm
JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256("123456".getBytes()));
Time Validation
There are separate validation methods for time-related claims, mainly including:
- The not-before time (
JWTPayload#NOT_BEFORE
) cannot be later than the current time. - The expiration time (
JWTPayload#EXPIRES_AT
) cannot be earlier than the current time. - The issued-at time (
JWTPayload#ISSUED_AT
) cannot be later than the current time.
The general timeline is:
(Issued-at time)———(Not-before time)———(Current time)———(Expiration time)
There is generally no requirement for the order of the issued-at time and the not-before time, as long as they are both earlier than the current time.
final String token = JWT.create()
// Set the issued-at time
.setIssuedAt(DateUtil.date())
.setKey("123456".getBytes())
.sign();
// Since only the issued-at time is defined, only check the issued-at time
JWTValidator.of(token).validateDate(DateUtil.date());