If present, this value is the timestamp when the JWT was created.
*
* @return the JWT {@code iat} value or {@code null} if not present.
+ * @deprecated since 0.14.0 in favor of {@link #issuedAt()}. This method will be removed before the
+ * JJWT 1.0 release.
*/
+ @Deprecated
Date getIssuedAt();
+ /**
+ * Returns the JWT If present, this value is the timestamp when the JWT was created.
+ *
+ * The default implementation returns {@code getIssuedAt().toInstant()} for compatibility with existing
+ * {@code Claims} implementations. Implementations are encouraged to override this method directly.
+ *
+ * @return the JWT {@code iat} value or {@code null} if not present.
+ * @since 0.14.0
+ */
+ default Instant issuedAt() {
+ Date date = getIssuedAt();
+ return date != null ? date.toInstant() : null;
+ }
+
/**
* Returns the JWTs , Identifiable {
* Returns the JWTs claim ({@code claimName}) value as a {@code requiredType} instance, or {@code null} if not
* present.
*
- * JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. Anything more
+ *
JJWT only converts simple String, Date, Instant, Long, Integer, Short and Byte types automatically. Anything more
* complex is expected to be already converted to your desired type by the JSON parser. You may specify a custom
* JSON processor using the {@code JwtParserBuilder}'s
* {@link JwtParserBuilder#json(io.jsonwebtoken.io.Deserializer) json(Deserializer)} method. See the JJWT
diff --git a/api/src/main/java/io/jsonwebtoken/ClaimsMutator.java b/api/src/main/java/io/jsonwebtoken/ClaimsMutator.java
index 1fdca1e43..5515ebcd3 100644
--- a/api/src/main/java/io/jsonwebtoken/ClaimsMutator.java
+++ b/api/src/main/java/io/jsonwebtoken/ClaimsMutator.java
@@ -17,6 +17,7 @@
import io.jsonwebtoken.lang.NestedCollection;
+import java.time.Instant;
import java.util.Collection;
import java.util.Date;
@@ -124,7 +125,7 @@ public interface ClaimsMutator> {
* @param exp the JWT {@code exp} value or {@code null} to remove the property from the JSON map.
* @return the {@code Claims} instance for method chaining.
* @deprecated since 0.12.0 in favor of the shorter and more modern builder-style named
- * {@link #expiration(Date)}. This method will be removed before the JJWT 1.0 release.
+ * {@link #expiration(Instant)}. This method will be removed before the JJWT 1.0 release.
*/
@Deprecated
T setExpiration(Date exp);
@@ -139,9 +140,31 @@ public interface ClaimsMutator> {
* @param exp the JWT {@code exp} value or {@code null} to remove the property from the JSON map.
* @return the {@code Claims} instance for method chaining.
* @since 0.12.0
+ * @deprecated since 0.14.0 in favor of {@link #expiration(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
+ @Deprecated
T expiration(Date exp);
+ /**
+ * Sets the JWT
+ * exp (expiration) timestamp claim. A {@code null} value will remove the property from the
+ * JSON Claims map.
+ *
+ * A JWT obtained after this timestamp should not be used.
+ *
+ * The default implementation delegates to {@link #expiration(Date)} for compatibility with existing
+ * {@code ClaimsMutator} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param exp the JWT {@code exp} value or {@code null} to remove the property from the JSON map.
+ * @return the {@code Claims} instance for method chaining.
+ * @since 0.14.0
+ */
+ default T expiration(Instant exp) {
+ return expiration(exp != null ? Date.from(exp) : null);
+ }
+
/**
* Sets the JWT
* nbf (not before) timestamp claim. A {@code null} value will remove the property from the
@@ -152,7 +175,7 @@ public interface ClaimsMutator> {
* @param nbf the JWT {@code nbf} value or {@code null} to remove the property from the JSON map.
* @return the {@code Claims} instance for method chaining.
* @deprecated since 0.12.0 in favor of the shorter and more modern builder-style named
- * {@link #notBefore(Date)}. This method will be removed before the JJWT 1.0 release.
+ * {@link #notBefore(Instant)}. This method will be removed before the JJWT 1.0 release.
*/
@Deprecated
T setNotBefore(Date nbf);
@@ -167,9 +190,31 @@ public interface ClaimsMutator> {
* @param nbf the JWT {@code nbf} value or {@code null} to remove the property from the JSON map.
* @return the {@code Claims} instance for method chaining.
* @since 0.12.0
+ * @deprecated since 0.14.0 in favor of {@link #notBefore(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
+ @Deprecated
T notBefore(Date nbf);
+ /**
+ * Sets the JWT
+ * nbf (not before) timestamp claim. A {@code null} value will remove the property from the
+ * JSON Claims map.
+ *
+ * A JWT obtained before this timestamp should not be used.
+ *
+ * The default implementation delegates to {@link #notBefore(Date)} for compatibility with existing
+ * {@code ClaimsMutator} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param nbf the JWT {@code nbf} value or {@code null} to remove the property from the JSON map.
+ * @return the {@code Claims} instance for method chaining.
+ * @since 0.14.0
+ */
+ default T notBefore(Instant nbf) {
+ return notBefore(nbf != null ? Date.from(nbf) : null);
+ }
+
/**
* Sets the JWT
* iat (issued at) timestamp claim. A {@code null} value will remove the property from the
@@ -180,7 +225,7 @@ public interface ClaimsMutator> {
* @param iat the JWT {@code iat} value or {@code null} to remove the property from the JSON map.
* @return the {@code Claims} instance for method chaining.
* @deprecated since 0.12.0 in favor of the shorter and more modern builder-style named
- * {@link #issuedAt(Date)}. This method will be removed before the JJWT 1.0 release.
+ * {@link #issuedAt(Instant)}. This method will be removed before the JJWT 1.0 release.
*/
@Deprecated
T setIssuedAt(Date iat);
@@ -195,9 +240,31 @@ public interface ClaimsMutator> {
* @param iat the JWT {@code iat} value or {@code null} to remove the property from the JSON map.
* @return the {@code Claims} instance for method chaining.
* @since 0.12.0
+ * @deprecated since 0.14.0 in favor of {@link #issuedAt(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
+ @Deprecated
T issuedAt(Date iat);
+ /**
+ * Sets the JWT
+ * iat (issued at) timestamp claim. A {@code null} value will remove the property from the
+ * JSON Claims map.
+ *
+ * The value is the timestamp when the JWT was created.
+ *
+ * The default implementation delegates to {@link #issuedAt(Date)} for compatibility with existing
+ * {@code ClaimsMutator} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param iat the JWT {@code iat} value or {@code null} to remove the property from the JSON map.
+ * @return the {@code Claims} instance for method chaining.
+ * @since 0.14.0
+ */
+ default T issuedAt(Instant iat) {
+ return issuedAt(iat != null ? Date.from(iat) : null);
+ }
+
/**
* Sets the JWT
* jti (JWT ID) claim. A {@code null} value will remove the property from the JSON Claims map.
diff --git a/api/src/main/java/io/jsonwebtoken/Clock.java b/api/src/main/java/io/jsonwebtoken/Clock.java
index 680251628..3ffce649d 100644
--- a/api/src/main/java/io/jsonwebtoken/Clock.java
+++ b/api/src/main/java/io/jsonwebtoken/Clock.java
@@ -15,6 +15,7 @@
*/
package io.jsonwebtoken;
+import java.time.Instant;
import java.util.Date;
/**
@@ -29,6 +30,24 @@ public interface Clock {
* Returns the clock's current timestamp at the instant the method is invoked.
*
* @return the clock's current timestamp at the instant the method is invoked.
+ * @deprecated since 0.14.0 in favor of {@link #instant()}. This method will be removed before the
+ * JJWT 1.0 release. Until then, new {@code Clock} implementations may implement this method as
+ * {@code return Date.from(instant());} and override {@link #instant()} directly.
*/
+ @Deprecated
Date now();
+
+ /**
+ * Returns the clock's current timestamp at the instant the method is invoked.
+ *
+ * The default implementation returns {@code now().toInstant()} for compatibility with existing
+ * {@code Clock} implementations that only implement {@link #now()}. Implementations are encouraged
+ * to override this method directly.
+ *
+ * @return the clock's current timestamp at the instant the method is invoked.
+ * @since 0.14.0
+ */
+ default Instant instant() {
+ return now().toInstant();
+ }
}
diff --git a/api/src/main/java/io/jsonwebtoken/JwtBuilder.java b/api/src/main/java/io/jsonwebtoken/JwtBuilder.java
index 634800851..a5aa489d5 100644
--- a/api/src/main/java/io/jsonwebtoken/JwtBuilder.java
+++ b/api/src/main/java/io/jsonwebtoken/JwtBuilder.java
@@ -40,6 +40,7 @@
import java.security.SecureRandom;
import java.security.interfaces.ECKey;
import java.security.interfaces.RSAKey;
+import java.time.Instant;
import java.util.Date;
import java.util.Map;
@@ -498,7 +499,6 @@ public interface JwtBuilder extends ClaimsMutator {
* @return the builder instance for method chaining.
*/
@Override
- // for better/targeted JavaDoc
JwtBuilder issuer(String iss);
/**
@@ -512,7 +512,6 @@ public interface JwtBuilder extends ClaimsMutator {
* @return the builder instance for method chaining.
*/
@Override
- // for better/targeted JavaDoc
JwtBuilder subject(String sub);
/**
@@ -527,11 +526,36 @@ public interface JwtBuilder extends ClaimsMutator {
*
* @param exp the JWT {@code exp} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
+ * @deprecated since 0.14.0 in favor of {@link #expiration(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
- @Override
- // for better/targeted JavaDoc
+ @Override
+ @Deprecated
JwtBuilder expiration(Date exp);
+ /**
+ * Sets the JWT Claims
+ * exp (expiration) claim. A {@code null} value will remove the property from the Claims.
+ *
+ * A JWT obtained after this timestamp should not be used.
+ *
+ * This is a convenience wrapper for:
+ *
+ * {@link #claims()}.{@link ClaimsMutator#expiration(Instant) expiration(exp)}.{@link BuilderClaims#and() and()}
+ *
+ * The default implementation delegates to {@link #expiration(Date)} for compatibility with existing
+ * {@code JwtBuilder} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param exp the JWT {@code exp} value or {@code null} to remove the property from the Claims map.
+ * @return the builder instance for method chaining.
+ * @since 0.14.0
+ */
+ @Override
+ default JwtBuilder expiration(Instant exp) {
+ return expiration(exp != null ? Date.from(exp) : null);
+ }
+
/**
* Sets the JWT Claims
* nbf (not before) claim. A {@code null} value will remove the property from the Claims.
@@ -544,11 +568,36 @@ public interface JwtBuilder extends ClaimsMutator {
*
* @param nbf the JWT {@code nbf} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
+ * @deprecated since 0.14.0 in favor of {@link #notBefore(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
@Override
- // for better/targeted JavaDoc
+ @Deprecated
JwtBuilder notBefore(Date nbf);
+ /**
+ * Sets the JWT Claims
+ * nbf (not before) claim. A {@code null} value will remove the property from the Claims.
+ *
+ * A JWT obtained before this timestamp should not be used.
+ *
+ * This is a convenience wrapper for:
+ *
+ * {@link #claims()}.{@link ClaimsMutator#notBefore(Instant) notBefore(nbf)}.{@link BuilderClaims#and() and()}
+ *
+ * The default implementation delegates to {@link #notBefore(Date)} for compatibility with existing
+ * {@code JwtBuilder} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param nbf the JWT {@code nbf} value or {@code null} to remove the property from the Claims map.
+ * @return the builder instance for method chaining.
+ * @since 0.14.0
+ */
+ @Override
+ default JwtBuilder notBefore(Instant nbf) {
+ return notBefore(nbf != null ? Date.from(nbf) : null);
+ }
+
/**
* Sets the JWT Claims
* iat (issued at) claim. A {@code null} value will remove the property from the Claims.
@@ -561,11 +610,36 @@ public interface JwtBuilder extends ClaimsMutator {
*
* @param iat the JWT {@code iat} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
+ * @deprecated since 0.14.0 in favor of {@link #issuedAt(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
@Override
- // for better/targeted JavaDoc
+ @Deprecated
JwtBuilder issuedAt(Date iat);
+ /**
+ * Sets the JWT Claims
+ * iat (issued at) claim. A {@code null} value will remove the property from the Claims.
+ *
+ * The value is the timestamp when the JWT was created.
+ *
+ * This is a convenience wrapper for:
+ *
+ * {@link #claims()}.{@link ClaimsMutator#issuedAt(Instant) issuedAt(iat)}.{@link BuilderClaims#and() and()}
+ *
+ * The default implementation delegates to {@link #issuedAt(Date)} for compatibility with existing
+ * {@code JwtBuilder} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param iat the JWT {@code iat} value or {@code null} to remove the property from the Claims map.
+ * @return the builder instance for method chaining.
+ * @since 0.14.0
+ */
+ @Override
+ default JwtBuilder issuedAt(Instant iat) {
+ return issuedAt(iat != null ? Date.from(iat) : null);
+ }
+
/**
* Sets the JWT Claims
* jti (JWT ID) claim. A {@code null} value will remove the property from the Claims.
@@ -582,7 +656,6 @@ public interface JwtBuilder extends ClaimsMutator {
* @return the builder instance for method chaining.
*/
@Override
- // for better/targeted JavaDoc
JwtBuilder id(String jti);
/**
diff --git a/api/src/main/java/io/jsonwebtoken/JwtParserBuilder.java b/api/src/main/java/io/jsonwebtoken/JwtParserBuilder.java
index 79936695a..a77dbd948 100644
--- a/api/src/main/java/io/jsonwebtoken/JwtParserBuilder.java
+++ b/api/src/main/java/io/jsonwebtoken/JwtParserBuilder.java
@@ -31,6 +31,7 @@
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
+import java.time.Instant;
import java.util.Date;
import java.util.Map;
@@ -194,9 +195,31 @@ public interface JwtParserBuilder extends Builder {
* @return the parser builder for method chaining.
* @see MissingClaimException
* @see IncorrectClaimException
+ * @deprecated since 0.14.0 in favor of {@link #requireIssuedAt(Instant)}. This method will be removed
+ * before the JJWT 1.0 release.
*/
+ @Deprecated
JwtParserBuilder requireIssuedAt(Date issuedAt);
+ /**
+ * Ensures that the specified {@code iat} exists in the parsed JWT. If missing or if the parsed
+ * value does not equal the specified value, an exception will be thrown indicating that the
+ * JWT is invalid and may not be used.
+ *
+ * The default implementation delegates to {@link #requireIssuedAt(Date)} for compatibility with existing
+ * {@code JwtParserBuilder} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param issuedAt the required value of the {@code iat} header parameter.
+ * @return the parser builder for method chaining.
+ * @see MissingClaimException
+ * @see IncorrectClaimException
+ * @since 0.14.0
+ */
+ default JwtParserBuilder requireIssuedAt(Instant issuedAt) {
+ return requireIssuedAt(issuedAt != null ? Date.from(issuedAt) : null);
+ }
+
/**
* Ensures that the specified {@code exp} exists in the parsed JWT. If missing or if the parsed
* value does not equal the specified value, an exception will be thrown indicating that the
@@ -206,21 +229,65 @@ public interface JwtParserBuilder extends Builder {
* @return the parser builder for method chaining.
* @see MissingClaimException
* @see IncorrectClaimException
+ * @deprecated since 0.14.0 in favor of {@link #requireExpiration(Instant)}. This method will be removed
+ * before the JJWT 1.0 release.
*/
+ @Deprecated
JwtParserBuilder requireExpiration(Date expiration);
+ /**
+ * Ensures that the specified {@code exp} exists in the parsed JWT. If missing or if the parsed
+ * value does not equal the specified value, an exception will be thrown indicating that the
+ * JWT is invalid and may not be used.
+ *
+ * The default implementation delegates to {@link #requireExpiration(Date)} for compatibility with existing
+ * {@code JwtParserBuilder} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param expiration the required value of the {@code exp} header parameter.
+ * @return the parser builder for method chaining.
+ * @see MissingClaimException
+ * @see IncorrectClaimException
+ * @since 0.14.0
+ */
+ default JwtParserBuilder requireExpiration(Instant expiration) {
+ return requireExpiration(expiration != null ? Date.from(expiration) : null);
+ }
+
/**
* Ensures that the specified {@code nbf} exists in the parsed JWT. If missing or if the parsed
* value does not equal the specified value, an exception will be thrown indicating that the
* JWT is invalid and may not be used.
*
- * @param notBefore the required value of the {@code npf} header parameter.
+ * @param notBefore the required value of the {@code nbf} header parameter.
* @return the parser builder for method chaining
* @see MissingClaimException
* @see IncorrectClaimException
+ * @deprecated since 0.14.0 in favor of {@link #requireNotBefore(Instant)}. This method will be removed
+ * before the JJWT 1.0 release.
*/
+ @Deprecated
JwtParserBuilder requireNotBefore(Date notBefore);
+ /**
+ * Ensures that the specified {@code nbf} exists in the parsed JWT. If missing or if the parsed
+ * value does not equal the specified value, an exception will be thrown indicating that the
+ * JWT is invalid and may not be used.
+ *
+ * The default implementation delegates to {@link #requireNotBefore(Date)} for compatibility with existing
+ * {@code JwtParserBuilder} implementations. Implementations are encouraged to override this method
+ * directly.
+ *
+ * @param notBefore the required value of the {@code nbf} header parameter.
+ * @return the parser builder for method chaining
+ * @see MissingClaimException
+ * @see IncorrectClaimException
+ * @since 0.14.0
+ */
+ default JwtParserBuilder requireNotBefore(Instant notBefore) {
+ return requireNotBefore(notBefore != null ? Date.from(notBefore) : null);
+ }
+
/**
* Ensures that the specified {@code claimName} exists in the parsed JWT. If missing or if the parsed
* value does not equal the specified value, an exception will be thrown indicating that the
@@ -236,7 +303,7 @@ public interface JwtParserBuilder extends Builder {
/**
* Sets the {@link Clock} that determines the timestamp to use when validating the parsed JWT.
- * The parser uses a default Clock implementation that simply returns {@code new Date()} when called.
+ * The parser uses a default Clock implementation that simply returns {@code Instant.now()} when called.
*
* @param clock a {@code Clock} object to return the timestamp to use when validating the parsed JWT.
* @return the parser builder for method chaining.
@@ -248,7 +315,7 @@ public interface JwtParserBuilder extends Builder {
/**
* Sets the {@link Clock} that determines the timestamp to use when validating the parsed JWT.
- * The parser uses a default Clock implementation that simply returns {@code new Date()} when called.
+ * The parser uses a default Clock implementation that simply returns {@code Instant.now()} when called.
*
* @param clock a {@code Clock} object to return the timestamp to use when validating the parsed JWT.
* @return the parser builder for method chaining.
diff --git a/api/src/main/java/io/jsonwebtoken/lang/DateFormats.java b/api/src/main/java/io/jsonwebtoken/lang/DateFormats.java
index 6a3b501b2..f084453dd 100644
--- a/api/src/main/java/io/jsonwebtoken/lang/DateFormats.java
+++ b/api/src/main/java/io/jsonwebtoken/lang/DateFormats.java
@@ -18,7 +18,13 @@
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.time.format.ResolverStyle;
import java.util.Date;
+import java.util.Locale;
import java.util.TimeZone;
/**
@@ -35,23 +41,29 @@ private DateFormats() {
private static final String ISO_8601_MILLIS_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
- private static final ThreadLocal ISO_8601 = new ThreadLocal() {
- @Override
- protected DateFormat initialValue() {
- SimpleDateFormat format = new SimpleDateFormat(ISO_8601_PATTERN);
- format.setTimeZone(TimeZone.getTimeZone("UTC"));
- return format;
- }
- };
-
- private static final ThreadLocal ISO_8601_MILLIS = new ThreadLocal() {
- @Override
- protected DateFormat initialValue() {
- SimpleDateFormat format = new SimpleDateFormat(ISO_8601_MILLIS_PATTERN);
- format.setTimeZone(TimeZone.getTimeZone("UTC"));
- return format;
- }
- };
+ // SimpleDateFormat is only used by the deprecated parseIso8601Date method in order to retain its lenient parsing
+ // behavior until it is removed. A new instance is created per call (SimpleDateFormat is not thread-safe) instead
+ // of being cached in a ThreadLocal, which would otherwise never be cleaned up in pooled threads. All formatting
+ // uses the thread-safe DateTimeFormatter instances below.
+ private static DateFormat legacyFormat(String pattern) {
+ SimpleDateFormat format = new SimpleDateFormat(pattern);
+ format.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return format;
+ }
+
+ // 'uuuu' (proleptic year) instead of 'yyyy' (year-of-era) so that ResolverStyle.STRICT doesn't require an era.
+ // DateTimeFormatter instances are immutable and thread-safe, so no ThreadLocal is needed.
+ private static final DateTimeFormatter ISO_8601_FORMATTER = isoFormatter("uuuu-MM-dd'T'HH:mm:ss'Z'");
+
+ private static final DateTimeFormatter ISO_8601_MILLIS_FORMATTER = isoFormatter("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'");
+
+ private static final DateTimeFormatter ISO_8601_PARSER = isoFormatter("uuuu-MM-dd'T'HH:mm:ss[.SSS]'Z'");
+
+ private static DateTimeFormatter isoFormatter(String pattern) {
+ return DateTimeFormatter.ofPattern(pattern, Locale.ROOT)
+ .withZone(ZoneOffset.UTC)
+ .withResolverStyle(ResolverStyle.STRICT);
+ }
/**
* Return an ISO-8601-formatted string with millisecond precision representing the
@@ -59,7 +71,10 @@ protected DateFormat initialValue() {
*
* @param date the date for which to create an ISO-8601-formatted string
* @return the date represented as an ISO-8601-formatted string with millisecond precision.
+ * @deprecated since 0.14.0 in favor of {@link #formatIso8601(Instant)}. This method will be removed before the
+ * JJWT 1.0 release.
*/
+ @Deprecated
public static String formatIso8601(Date date) {
return formatIso8601(date, true);
}
@@ -68,15 +83,20 @@ public static String formatIso8601(Date date) {
* Returns an ISO-8601-formatted string with optional millisecond precision for the specified
* {@code date}.
*
+ * As of 0.14.0, this method delegates to {@link #formatIso8601(Instant, boolean)}. Output is identical to
+ * previous versions for any date between the Gregorian calendar cutover (1582-10-15) and the year 9999. Earlier
+ * dates are formatted using the proleptic Gregorian calendar instead of the Julian calendar, and years after
+ * 9999 are prefixed with a {@code +} sign as required by ISO-8601.
+ *
* @param date the date for which to create an ISO-8601-formatted string
* @param includeMillis whether to include millisecond notation within the string.
* @return the date represented as an ISO-8601-formatted string with optional millisecond precision.
+ * @deprecated since 0.14.0 in favor of {@link #formatIso8601(Instant, boolean)}. This method will be removed
+ * before the JJWT 1.0 release.
*/
+ @Deprecated
public static String formatIso8601(Date date, boolean includeMillis) {
- if (includeMillis) {
- return ISO_8601_MILLIS.get().format(date);
- }
- return ISO_8601.get().format(date);
+ return formatIso8601(date.toInstant(), includeMillis);
}
/**
@@ -86,13 +106,71 @@ public static String formatIso8601(Date date, boolean includeMillis) {
* @param s the ISO-8601-formatted string to parse
* @return the string's corresponding {@link Date} instance.
* @throws ParseException if the specified date string is not a validly-formatted ISO-8601 string.
+ * @deprecated since 0.14.0 in favor of {@link #parseIso8601Instant(String)}. This method will be removed before
+ * the JJWT 1.0 release.
*/
+ @Deprecated
public static Date parseIso8601Date(String s) throws ParseException {
Assert.notNull(s, "String argument cannot be null.");
- if (s.lastIndexOf('.') > -1) { //assume ISO-8601 with milliseconds
- return ISO_8601_MILLIS.get().parse(s);
- } else { //assume ISO-8601 without millis:
- return ISO_8601.get().parse(s);
+ // assume ISO-8601 with milliseconds if there is a '.', otherwise assume ISO-8601 without millis:
+ String pattern = s.lastIndexOf('.') > -1 ? ISO_8601_MILLIS_PATTERN : ISO_8601_PATTERN;
+ return legacyFormat(pattern).parse(s);
+ }
+
+ /**
+ * Return an ISO-8601-formatted string with millisecond precision representing the
+ * specified {@code instant}. Any sub-millisecond precision is truncated.
+ *
+ * @param instant the instant for which to create an ISO-8601-formatted string
+ * @return the instant represented as an ISO-8601-formatted string with millisecond precision.
+ * @since 0.14.0
+ */
+ public static String formatIso8601(Instant instant) {
+ return formatIso8601(instant, true);
+ }
+
+ /**
+ * Returns an ISO-8601-formatted string with optional millisecond precision for the specified
+ * {@code instant}. Any precision beyond what is included in the string is truncated.
+ *
+ * For any instant on or after the Gregorian calendar cutover (1582-10-15), the output is identical to that
+ * of {@link #formatIso8601(Date, boolean)} for the equivalent {@code Date}. Earlier instants are formatted
+ * using the proleptic Gregorian calendar as required by ISO-8601, whereas the {@code Date} variant uses the
+ * Julian calendar.
+ *
+ * @param instant the instant for which to create an ISO-8601-formatted string
+ * @param includeMillis whether to include millisecond notation within the string.
+ * @return the instant represented as an ISO-8601-formatted string with optional millisecond precision.
+ * @since 0.14.0
+ */
+ public static String formatIso8601(Instant instant, boolean includeMillis) {
+ Assert.notNull(instant, "Instant argument cannot be null.");
+ DateTimeFormatter formatter = includeMillis ? ISO_8601_MILLIS_FORMATTER : ISO_8601_FORMATTER;
+ return formatter.format(instant);
+ }
+
+ /**
+ * Parse the specified ISO-8601-formatted date string and return the corresponding {@link Instant}. The
+ * date string may optionally contain millisecond notation, and those milliseconds will be represented accordingly.
+ *
+ * Unlike {@link #parseIso8601Date(String)}, parsing is strict: out-of-range field values (such as month
+ * {@code 13}) and trailing characters are rejected instead of being silently adjusted or ignored, and the
+ * millisecond notation, if present, must have exactly three digits. Also, dates before the Gregorian calendar
+ * cutover (1582-10-15) are interpreted using the proleptic Gregorian calendar instead of the Julian calendar.
+ *
+ * @param s the ISO-8601-formatted string to parse
+ * @return the string's corresponding {@link Instant}.
+ * @throws ParseException if the specified date string is not a validly-formatted ISO-8601 string.
+ * @since 0.14.0
+ */
+ public static Instant parseIso8601Instant(String s) throws ParseException {
+ Assert.notNull(s, "String argument cannot be null.");
+ try {
+ return ISO_8601_PARSER.parse(s, Instant::from);
+ } catch (DateTimeParseException e) {
+ ParseException pe = new ParseException(e.getMessage(), e.getErrorIndex());
+ pe.initCause(e);
+ throw pe;
}
}
}
diff --git a/api/src/test/groovy/io/jsonwebtoken/ClaimsMutatorTest.groovy b/api/src/test/groovy/io/jsonwebtoken/ClaimsMutatorTest.groovy
new file mode 100644
index 000000000..c426f368d
--- /dev/null
+++ b/api/src/test/groovy/io/jsonwebtoken/ClaimsMutatorTest.groovy
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.*
+
+class ClaimsMutatorTest {
+
+ private static final Instant INSTANT = Instant.ofEpochMilli(1700000000123L)
+
+ @Test
+ void testDefaultExpirationDelegatesToDate() {
+ def m = new LegacyMutator()
+ assertSame m, m.expiration(INSTANT)
+ assertEquals Date.from(INSTANT), m.values.exp
+ }
+
+ @Test
+ void testDefaultExpirationNull() {
+ def m = new LegacyMutator()
+ assertSame m, m.expiration((Instant) null)
+ assertTrue m.values.containsKey('exp')
+ assertNull m.values.exp
+ }
+
+ @Test
+ void testDefaultNotBeforeDelegatesToDate() {
+ def m = new LegacyMutator()
+ assertSame m, m.notBefore(INSTANT)
+ assertEquals Date.from(INSTANT), m.values.nbf
+ }
+
+ @Test
+ void testDefaultNotBeforeNull() {
+ def m = new LegacyMutator()
+ assertSame m, m.notBefore((Instant) null)
+ assertTrue m.values.containsKey('nbf')
+ assertNull m.values.nbf
+ }
+
+ @Test
+ void testDefaultIssuedAtDelegatesToDate() {
+ def m = new LegacyMutator()
+ assertSame m, m.issuedAt(INSTANT)
+ assertEquals Date.from(INSTANT), m.values.iat
+ }
+
+ @Test
+ void testDefaultIssuedAtNull() {
+ def m = new LegacyMutator()
+ assertSame m, m.issuedAt((Instant) null)
+ assertTrue m.values.containsKey('iat')
+ assertNull m.values.iat
+ }
+
+ /**
+ * A {@code ClaimsMutator} implementation written before the {@code Instant} variants existed: it only
+ * implements the {@code Date} methods, so the {@code Instant} ones fall back to the interface defaults.
+ */
+ static class LegacyMutator implements ClaimsMutator {
+
+ Map values = [:]
+
+ @Override
+ LegacyMutator expiration(Date exp) {
+ values.exp = exp
+ return this
+ }
+
+ @Override
+ LegacyMutator notBefore(Date nbf) {
+ values.nbf = nbf
+ return this
+ }
+
+ @Override
+ LegacyMutator issuedAt(Date iat) {
+ values.iat = iat
+ return this
+ }
+
+ @Override
+ LegacyMutator setExpiration(Date exp) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator setNotBefore(Date nbf) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator setIssuedAt(Date iat) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator setIssuer(String iss) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator issuer(String iss) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator setSubject(String sub) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator subject(String sub) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator setAudience(String aud) { throw new UnsupportedOperationException() }
+
+ @Override
+ AudienceCollection audience() { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator setId(String jti) { throw new UnsupportedOperationException() }
+
+ @Override
+ LegacyMutator id(String jti) { throw new UnsupportedOperationException() }
+ }
+}
diff --git a/api/src/test/groovy/io/jsonwebtoken/ClaimsTest.groovy b/api/src/test/groovy/io/jsonwebtoken/ClaimsTest.groovy
new file mode 100644
index 000000000..28baafe94
--- /dev/null
+++ b/api/src/test/groovy/io/jsonwebtoken/ClaimsTest.groovy
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.assertEquals
+import static org.junit.Assert.assertNull
+
+class ClaimsTest {
+
+ private static final Date DATE = new Date(1700000000123L)
+
+ private static Claims legacyClaims(Date exp, Date nbf, Date iat) {
+ return [
+ getExpiration: { -> exp },
+ getNotBefore : { -> nbf },
+ getIssuedAt : { -> iat }
+ ] as Claims
+ }
+
+ @Test
+ void testDefaultExpiration() {
+ assertEquals DATE.toInstant(), legacyClaims(DATE, null, null).expiration()
+ }
+
+ @Test
+ void testDefaultExpirationNull() {
+ assertNull legacyClaims(null, DATE, DATE).expiration()
+ }
+
+ @Test
+ void testDefaultNotBefore() {
+ assertEquals DATE.toInstant(), legacyClaims(null, DATE, null).notBefore()
+ }
+
+ @Test
+ void testDefaultNotBeforeNull() {
+ assertNull legacyClaims(DATE, null, DATE).notBefore()
+ }
+
+ @Test
+ void testDefaultIssuedAt() {
+ assertEquals DATE.toInstant(), legacyClaims(null, null, DATE).issuedAt()
+ }
+
+ @Test
+ void testDefaultIssuedAtNull() {
+ assertNull legacyClaims(DATE, DATE, null).issuedAt()
+ }
+
+ @Test
+ void testDefaultInstantAccessorsPreserveMillis() {
+ def claims = legacyClaims(new Date(1L), new Date(2L), new Date(3L))
+ assertEquals Instant.ofEpochMilli(1L), claims.expiration()
+ assertEquals Instant.ofEpochMilli(2L), claims.notBefore()
+ assertEquals Instant.ofEpochMilli(3L), claims.issuedAt()
+ }
+}
diff --git a/api/src/test/groovy/io/jsonwebtoken/ClockTest.groovy b/api/src/test/groovy/io/jsonwebtoken/ClockTest.groovy
new file mode 100644
index 000000000..85af5069d
--- /dev/null
+++ b/api/src/test/groovy/io/jsonwebtoken/ClockTest.groovy
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.assertEquals
+
+class ClockTest {
+
+ @Test
+ void testDefaultInstantDelegatesToNow() {
+ def date = new Date(1700000000123L)
+ Clock clock = new Clock() {
+ @Override
+ Date now() {
+ return date
+ }
+ }
+ assertEquals date.toInstant(), clock.instant()
+ }
+
+ @Test
+ void testDefaultInstantWithLambdaClock() {
+ def date = new Date(1700000000123L)
+ Clock clock = { -> date } as Clock
+ assertEquals Instant.ofEpochMilli(1700000000123L), clock.instant()
+ }
+
+ @Test
+ void testDefaultInstantReflectsEachNowInvocation() {
+ def millis = 1000L
+ Clock clock = { -> new Date(millis++) } as Clock
+ assertEquals Instant.ofEpochMilli(1000L), clock.instant()
+ assertEquals Instant.ofEpochMilli(1001L), clock.instant()
+ }
+
+ @Test
+ void testOverriddenInstant() {
+ def fixed = Instant.ofEpochSecond(1700000000L, 123456789L)
+ Clock clock = new Clock() {
+ @Override
+ Date now() {
+ return Date.from(instant())
+ }
+
+ @Override
+ Instant instant() {
+ return fixed
+ }
+ }
+ assertEquals fixed, clock.instant()
+ assertEquals Date.from(fixed), clock.now()
+ }
+}
diff --git a/api/src/test/groovy/io/jsonwebtoken/JwtBuilderTest.groovy b/api/src/test/groovy/io/jsonwebtoken/JwtBuilderTest.groovy
new file mode 100644
index 000000000..bde0d6998
--- /dev/null
+++ b/api/src/test/groovy/io/jsonwebtoken/JwtBuilderTest.groovy
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.*
+
+class JwtBuilderTest {
+
+ private static final Instant INSTANT = Instant.ofEpochMilli(1700000000123L)
+
+ @Test
+ void testDefaultExpirationDelegatesToDate() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.expiration(INSTANT)
+ assertEquals Date.from(INSTANT), builder.values.exp
+ }
+
+ @Test
+ void testDefaultExpirationNull() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.expiration((Instant) null)
+ assertTrue builder.values.containsKey('exp')
+ assertNull builder.values.exp
+ }
+
+ @Test
+ void testDefaultNotBeforeDelegatesToDate() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.notBefore(INSTANT)
+ assertEquals Date.from(INSTANT), builder.values.nbf
+ }
+
+ @Test
+ void testDefaultNotBeforeNull() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.notBefore((Instant) null)
+ assertTrue builder.values.containsKey('nbf')
+ assertNull builder.values.nbf
+ }
+
+ @Test
+ void testDefaultIssuedAtDelegatesToDate() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.issuedAt(INSTANT)
+ assertEquals Date.from(INSTANT), builder.values.iat
+ }
+
+ @Test
+ void testDefaultIssuedAtNull() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.issuedAt((Instant) null)
+ assertTrue builder.values.containsKey('iat')
+ assertNull builder.values.iat
+ }
+
+ /**
+ * Creates a {@code JwtBuilder} written before the {@code Instant} variants existed: only the {@code Date}
+ * methods are implemented (by {@link LegacyJwtBuilder}); Groovy generates the remaining abstract methods, so the
+ * {@code Instant} methods run their interface default implementations.
+ */
+ private static LegacyJwtBuilder legacyBuilder() {
+ return [:] as LegacyJwtBuilder
+ }
+
+ static abstract class LegacyJwtBuilder implements JwtBuilder {
+
+ Map values = [:]
+
+ @Override
+ JwtBuilder expiration(Date exp) {
+ values.exp = exp
+ return this
+ }
+
+ @Override
+ JwtBuilder notBefore(Date nbf) {
+ values.nbf = nbf
+ return this
+ }
+
+ @Override
+ JwtBuilder issuedAt(Date iat) {
+ values.iat = iat
+ return this
+ }
+ }
+}
diff --git a/api/src/test/groovy/io/jsonwebtoken/JwtParserBuilderTest.groovy b/api/src/test/groovy/io/jsonwebtoken/JwtParserBuilderTest.groovy
new file mode 100644
index 000000000..7eb125ddb
--- /dev/null
+++ b/api/src/test/groovy/io/jsonwebtoken/JwtParserBuilderTest.groovy
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.*
+
+class JwtParserBuilderTest {
+
+ private static final Instant INSTANT = Instant.ofEpochMilli(1700000000123L)
+
+ @Test
+ void testDefaultRequireIssuedAtDelegatesToDate() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.requireIssuedAt(INSTANT)
+ assertEquals Date.from(INSTANT), builder.values.iat
+ }
+
+ @Test
+ void testDefaultRequireIssuedAtNull() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.requireIssuedAt((Instant) null)
+ assertTrue builder.values.containsKey('iat')
+ assertNull builder.values.iat
+ }
+
+ @Test
+ void testDefaultRequireExpirationDelegatesToDate() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.requireExpiration(INSTANT)
+ assertEquals Date.from(INSTANT), builder.values.exp
+ }
+
+ @Test
+ void testDefaultRequireExpirationNull() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.requireExpiration((Instant) null)
+ assertTrue builder.values.containsKey('exp')
+ assertNull builder.values.exp
+ }
+
+ @Test
+ void testDefaultRequireNotBeforeDelegatesToDate() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.requireNotBefore(INSTANT)
+ assertEquals Date.from(INSTANT), builder.values.nbf
+ }
+
+ @Test
+ void testDefaultRequireNotBeforeNull() {
+ def builder = legacyBuilder()
+ assertSame builder, builder.requireNotBefore((Instant) null)
+ assertTrue builder.values.containsKey('nbf')
+ assertNull builder.values.nbf
+ }
+
+ /**
+ * Creates a {@code JwtParserBuilder} written before the {@code Instant} variants existed: only the
+ * {@code Date} methods are implemented (by {@link LegacyJwtParserBuilder}); Groovy generates the remaining
+ * abstract methods, so the {@code Instant} methods run their interface default implementations.
+ */
+ private static LegacyJwtParserBuilder legacyBuilder() {
+ return [:] as LegacyJwtParserBuilder
+ }
+
+ static abstract class LegacyJwtParserBuilder implements JwtParserBuilder {
+
+ Map values = [:]
+
+ @Override
+ JwtParserBuilder requireIssuedAt(Date issuedAt) {
+ values.iat = issuedAt
+ return this
+ }
+
+ @Override
+ JwtParserBuilder requireExpiration(Date expiration) {
+ values.exp = expiration
+ return this
+ }
+
+ @Override
+ JwtParserBuilder requireNotBefore(Date notBefore) {
+ values.nbf = notBefore
+ return this
+ }
+ }
+}
diff --git a/api/src/test/groovy/io/jsonwebtoken/lang/DateFormatsTest.groovy b/api/src/test/groovy/io/jsonwebtoken/lang/DateFormatsTest.groovy
index 39123bd5f..76d71b1ef 100644
--- a/api/src/test/groovy/io/jsonwebtoken/lang/DateFormatsTest.groovy
+++ b/api/src/test/groovy/io/jsonwebtoken/lang/DateFormatsTest.groovy
@@ -17,7 +17,9 @@ package io.jsonwebtoken.lang
import org.junit.Test
+import java.text.ParseException
import java.text.SimpleDateFormat
+import java.time.Instant
import static org.junit.Assert.*
@@ -26,8 +28,8 @@ class DateFormatsTest {
@Test //https://github.com/jwtk/jjwt/issues/291
void testUtcTimezone() {
- def iso8601 = DateFormats.ISO_8601.get()
- def iso8601Millis = DateFormats.ISO_8601_MILLIS.get()
+ def iso8601 = DateFormats.legacyFormat(DateFormats.ISO_8601_PATTERN)
+ def iso8601Millis = DateFormats.legacyFormat(DateFormats.ISO_8601_MILLIS_PATTERN)
assertTrue iso8601 instanceof SimpleDateFormat
assertTrue iso8601Millis instanceof SimpleDateFormat
@@ -37,4 +39,156 @@ class DateFormatsTest {
assertEquals utc, iso8601.getTimeZone()
assertEquals utc, iso8601Millis.getTimeZone()
}
+
+ @Test //https://github.com/jwtk/jjwt/issues/291
+ void testParseIso8601DateUsesUtc() {
+ assertEquals Instant.parse('2023-11-14T22:13:20Z'),
+ DateFormats.parseIso8601Date('2023-11-14T22:13:20Z').toInstant()
+ assertEquals Instant.parse('2023-11-14T22:13:20.123Z'),
+ DateFormats.parseIso8601Date('2023-11-14T22:13:20.123Z').toInstant()
+ }
+
+ @Test
+ void testParseIso8601DateRetainsLenientBehavior() {
+ // the deprecated Date variant must keep its pre-0.14.0 lenient SimpleDateFormat behavior:
+ assertEquals Instant.parse('2022-01-01T00:00:00Z'),
+ DateFormats.parseIso8601Date('2021-13-01T00:00:00Z').toInstant()
+ }
+
+ private static final List SAMPLES = [
+ Instant.EPOCH,
+ Instant.ofEpochMilli(1L),
+ Instant.ofEpochMilli(-1L), // before the epoch
+ Instant.ofEpochMilli(1700000000000L), // no millis
+ Instant.ofEpochMilli(1700000000123L),
+ Instant.ofEpochMilli(1700000000999L),
+ Instant.parse('1999-12-31T23:59:59.999Z'),
+ Instant.parse('2024-02-29T12:00:00.050Z'), // leap day
+ Instant.parse('9999-12-31T23:59:59.999Z'),
+ Instant.parse('1582-10-15T00:00:00Z') // first day of the Gregorian calendar
+ ]
+
+ private static String legacyFormat(Date date, boolean includeMillis) {
+ def pattern = includeMillis ? "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" : "yyyy-MM-dd'T'HH:mm:ss'Z'"
+ def format = new SimpleDateFormat(pattern)
+ format.setTimeZone(TimeZone.getTimeZone("UTC"))
+ return format.format(date)
+ }
+
+ /**
+ * Ensures the output is identical to the pre-0.14.0 {@code SimpleDateFormat}-based implementation for all dates
+ * between the Gregorian cutover and the year 9999.
+ */
+ @Test
+ void testFormatIso8601MatchesLegacySimpleDateFormat() {
+ for (Instant instant : SAMPLES) {
+ Date date = Date.from(instant)
+ for (boolean millis : [true, false]) {
+ String expected = legacyFormat(date, millis)
+ assertEquals expected, DateFormats.formatIso8601(date, millis)
+ assertEquals expected, DateFormats.formatIso8601(instant, millis)
+ }
+ assertEquals legacyFormat(date, true), DateFormats.formatIso8601(date)
+ }
+ }
+
+ @Test(expected = NullPointerException)
+ void testFormatIso8601DateNull() {
+ DateFormats.formatIso8601((Date) null)
+ }
+
+ @Test
+ void testFormatIso8601DateAfterYear9999() {
+ def date = Date.from(Instant.parse('+10000-01-01T00:00:00Z'))
+ assertEquals '+10000-01-01T00:00:00.000Z', DateFormats.formatIso8601(date)
+ }
+
+ @Test
+ void testFormatIso8601Instant() {
+ def instant = Instant.parse('2023-11-14T22:13:20.123Z')
+ assertEquals '2023-11-14T22:13:20.123Z', DateFormats.formatIso8601(instant)
+ assertEquals '2023-11-14T22:13:20.123Z', DateFormats.formatIso8601(instant, true)
+ assertEquals '2023-11-14T22:13:20Z', DateFormats.formatIso8601(instant, false)
+ }
+
+ @Test
+ void testFormatIso8601InstantTruncatesSubMillis() {
+ def instant = Instant.ofEpochSecond(1700000000L, 123999999L)
+ assertEquals '2023-11-14T22:13:20.123Z', DateFormats.formatIso8601(instant, true)
+ assertEquals '2023-11-14T22:13:20Z', DateFormats.formatIso8601(instant, false)
+ }
+
+ @Test(expected = IllegalArgumentException)
+ void testFormatIso8601InstantNull() {
+ DateFormats.formatIso8601((Instant) null)
+ }
+
+ /**
+ * Before the Gregorian cutover {@code SimpleDateFormat} used the Julian calendar, while {@code java.time} uses
+ * the proleptic Gregorian (ISO-8601) calendar. Both variants now yield the correct ISO-8601 string.
+ */
+ @Test
+ void testFormatIso8601BeforeGregorianCutover() {
+ def instant = Instant.parse('0001-01-01T00:00:00Z')
+ assertEquals '0001-01-01T00:00:00.000Z', DateFormats.formatIso8601(instant)
+ assertEquals '0001-01-01T00:00:00.000Z', DateFormats.formatIso8601(Date.from(instant))
+ assertEquals '0001-01-03T00:00:00.000Z', legacyFormat(Date.from(instant), true)
+ }
+
+ @Test
+ void testParseIso8601Instant() {
+ assertEquals Instant.parse('2023-11-14T22:13:20Z'), DateFormats.parseIso8601Instant('2023-11-14T22:13:20Z')
+ assertEquals Instant.parse('2023-11-14T22:13:20.123Z'),
+ DateFormats.parseIso8601Instant('2023-11-14T22:13:20.123Z')
+ }
+
+ @Test
+ void testParseIso8601InstantRoundTrip() {
+ for (Instant instant : SAMPLES) {
+ assertEquals instant, DateFormats.parseIso8601Instant(DateFormats.formatIso8601(instant, true))
+ assertEquals instant.getEpochSecond(),
+ DateFormats.parseIso8601Instant(DateFormats.formatIso8601(instant, false)).getEpochSecond()
+ }
+ }
+
+ @Test
+ void testParseIso8601InstantMatchesDate() {
+ for (Instant instant : SAMPLES) {
+ for (boolean millis : [true, false]) {
+ String s = DateFormats.formatIso8601(instant, millis)
+ assertEquals DateFormats.parseIso8601Date(s).toInstant(), DateFormats.parseIso8601Instant(s)
+ }
+ }
+ }
+
+ @Test(expected = IllegalArgumentException)
+ void testParseIso8601InstantNull() {
+ DateFormats.parseIso8601Instant(null)
+ }
+
+ @Test
+ void testParseIso8601InstantInvalid() {
+ def invalid = [
+ '',
+ 'not a date',
+ '2023-11-14', // no time
+ '2023-11-14T22:13:20', // no 'Z'
+ '2023-11-14T22:13:20+01:00', // offsets are not supported
+ '2023-11-14T22:13:20.12Z', // millis must have 3 digits
+ '2023-11-14T22:13:20.1234Z',
+ '2023-13-14T22:13:20Z', // month out of range
+ '2023-02-30T22:13:20Z', // day out of range (lenient parsing would roll over)
+ '2023-11-14T24:00:00Z', // hour out of range
+ '2023-11-14T22:13:20Zjunk' // trailing characters
+ ]
+ for (String s : invalid) {
+ try {
+ DateFormats.parseIso8601Instant(s)
+ fail("Expected ParseException for '$s'")
+ } catch (ParseException expected) {
+ assertNotNull expected.getMessage()
+ assertNotNull expected.getCause()
+ }
+ }
+ }
}
diff --git a/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonInstantTypeAdapter.java b/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonInstantTypeAdapter.java
new file mode 100644
index 000000000..453475b4d
--- /dev/null
+++ b/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonInstantTypeAdapter.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.gson.io;
+
+import com.google.gson.JsonParseException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import io.jsonwebtoken.lang.DateFormats;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.time.Instant;
+
+/**
+ * Gson {@link TypeAdapter} that writes {@link Instant} values as ISO-8601 strings with millisecond precision (e.g.
+ * {@code 2026-10-03T10:00:00.123Z}), consistent with how JJWT represents {@code java.util.Date} values in custom
+ * claims. When reading, ISO-8601 strings and integral numbers (milliseconds since the epoch) are supported.
+ *
+ * JJWT's default {@code Gson} instance already has this adapter registered. If you specify your own {@code Gson}
+ * instance and use {@code Instant} values in custom claims, register it via
+ * {@code gsonBuilder.registerTypeAdapter(Instant.class, GsonInstantTypeAdapter.INSTANCE)}.
+ *
+ * @since 0.14.0
+ */
+public final class GsonInstantTypeAdapter extends TypeAdapter {
+
+ public static final TypeAdapter INSTANCE = new GsonInstantTypeAdapter().nullSafe();
+
+ private GsonInstantTypeAdapter() {
+ }
+
+ @Override
+ public void write(JsonWriter out, Instant instant) throws IOException {
+ out.value(DateFormats.formatIso8601(instant));
+ }
+
+ @Override
+ public Instant read(JsonReader in) throws IOException {
+ if (in.peek() == JsonToken.NUMBER) {
+ return Instant.ofEpochMilli(in.nextLong());
+ }
+ String value = in.nextString();
+ try {
+ return DateFormats.parseIso8601Instant(value);
+ } catch (ParseException e) {
+ throw new JsonParseException("Unable to parse '" + value + "' as an ISO-8601 Instant: " +
+ e.getMessage(), e);
+ }
+ }
+}
diff --git a/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonSerializer.java b/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonSerializer.java
index e90d08d0c..92930bee2 100644
--- a/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonSerializer.java
+++ b/extensions/gson/src/main/java/io/jsonwebtoken/gson/io/GsonSerializer.java
@@ -28,6 +28,7 @@
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
public class GsonSerializer extends AbstractSerializer {
@@ -35,6 +36,7 @@ public class GsonSerializer extends AbstractSerializer {
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.registerTypeHierarchyAdapter(ConfidentialValue.class, GsonConfidentialValueSerializer.INSTANCE)
+ .registerTypeAdapter(Instant.class, GsonInstantTypeAdapter.INSTANCE)
.disableHtmlEscaping().create();
protected final Gson gson;
diff --git a/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonInstantTypeAdapterTest.groovy b/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonInstantTypeAdapterTest.groovy
new file mode 100644
index 000000000..4d91e357f
--- /dev/null
+++ b/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonInstantTypeAdapterTest.groovy
@@ -0,0 +1,67 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.gson.io
+
+import com.google.gson.Gson
+import com.google.gson.GsonBuilder
+import com.google.gson.JsonParseException
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.*
+
+class GsonInstantTypeAdapterTest {
+
+ private static final Gson GSON = new GsonBuilder()
+ .registerTypeAdapter(Instant, GsonInstantTypeAdapter.INSTANCE).create()
+
+ @Test
+ void testWrite() {
+ assertEquals '"2026-10-03T10:00:00.123Z"', GSON.toJson(Instant.parse('2026-10-03T10:00:00.123Z'))
+ }
+
+ @Test
+ void testWriteNull() {
+ assertEquals 'null', GsonInstantTypeAdapter.INSTANCE.toJson(null)
+ }
+
+ @Test
+ void testReadIso8601String() {
+ assertEquals Instant.parse('2026-10-03T10:00:00.123Z'),
+ GSON.fromJson('"2026-10-03T10:00:00.123Z"', Instant)
+ }
+
+ @Test
+ void testReadMillis() {
+ assertEquals Instant.ofEpochMilli(1791021600123L), GSON.fromJson('1791021600123', Instant)
+ }
+
+ @Test
+ void testReadNull() {
+ assertNull GSON.fromJson('null', Instant)
+ }
+
+ @Test
+ void testReadInvalidString() {
+ try {
+ GSON.fromJson('"hello"', Instant)
+ fail()
+ } catch (JsonParseException expected) {
+ assertTrue expected.getMessage().startsWith("Unable to parse 'hello' as an ISO-8601 Instant")
+ }
+ }
+}
diff --git a/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonSerializerTest.groovy b/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonSerializerTest.groovy
index d0b6b4b34..632a888d7 100644
--- a/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonSerializerTest.groovy
+++ b/extensions/gson/src/test/groovy/io/jsonwebtoken/gson/io/GsonSerializerTest.groovy
@@ -25,6 +25,8 @@ import io.jsonwebtoken.security.ConfidentialValue
import org.junit.Before
import org.junit.Test
+import java.time.Instant
+
import static org.junit.Assert.*
class GsonSerializerTest {
@@ -169,4 +171,11 @@ class GsonSerializerTest {
assertEquals msg, expected.message
}
}
+
+ @Test
+ void testInstant() {
+ def instant = Instant.parse('2026-10-03T10:00:00.123Z')
+ assertEquals '"2026-10-03T10:00:00.123Z"', ser(instant)
+ assertEquals '{"custom":"2026-10-03T10:00:00.123Z"}', ser([custom: instant])
+ }
}
diff --git a/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonInstantDeserializer.java b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonInstantDeserializer.java
new file mode 100644
index 000000000..0023cc332
--- /dev/null
+++ b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonInstantDeserializer.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.jackson.io;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
+import io.jsonwebtoken.lang.DateFormats;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.time.Instant;
+
+/**
+ * Deserializes {@link Instant} values from ISO-8601 strings (as written by {@link JacksonInstantSerializer}) or from
+ * integral numbers representing milliseconds since the epoch, consistent with JJWT's {@code Claims.get(name,
+ * Instant.class)} conversion heuristics, and without requiring the {@code jackson-datatype-jsr310} module.
+ *
+ * @since 0.14.0
+ */
+final class JacksonInstantDeserializer extends StdScalarDeserializer {
+
+ static final JacksonInstantDeserializer INSTANCE = new JacksonInstantDeserializer();
+
+ public JacksonInstantDeserializer() {
+ super(Instant.class);
+ }
+
+ @Override
+ public Instant deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
+ JsonToken token = p.currentToken();
+ if (token == JsonToken.VALUE_NUMBER_INT) {
+ return Instant.ofEpochMilli(p.getLongValue());
+ }
+ if (token == JsonToken.VALUE_STRING) {
+ String value = p.getText().trim();
+ try {
+ return DateFormats.parseIso8601Instant(value);
+ } catch (ParseException e) {
+ return (Instant) ctx.handleWeirdStringValue(Instant.class, value,
+ "not an ISO-8601-formatted string: %s", e.getMessage());
+ }
+ }
+ return (Instant) ctx.handleUnexpectedToken(Instant.class, p);
+ }
+}
diff --git a/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonInstantSerializer.java b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonInstantSerializer.java
new file mode 100644
index 000000000..65908de7c
--- /dev/null
+++ b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonInstantSerializer.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.jackson.io;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+import io.jsonwebtoken.lang.DateFormats;
+
+import java.io.IOException;
+import java.time.Instant;
+
+/**
+ * Serializes {@link Instant} values as ISO-8601 strings with millisecond precision (e.g.
+ * {@code 2026-10-03T10:00:00.123Z}), consistent with how JJWT represents {@code java.util.Date} values in custom
+ * claims, and without requiring the {@code jackson-datatype-jsr310} module.
+ *
+ * @since 0.14.0
+ */
+final class JacksonInstantSerializer extends StdSerializer {
+
+ static final JacksonInstantSerializer INSTANCE = new JacksonInstantSerializer();
+
+ public JacksonInstantSerializer() {
+ super(Instant.class);
+ }
+
+ @Override
+ public void serialize(Instant instant, JsonGenerator generator, SerializerProvider provider) throws IOException {
+ generator.writeString(DateFormats.formatIso8601(instant));
+ }
+}
diff --git a/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonSerializer.java b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonSerializer.java
index 5d8bca834..290256a44 100644
--- a/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonSerializer.java
+++ b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonSerializer.java
@@ -26,6 +26,7 @@
import io.jsonwebtoken.lang.Assert;
import java.io.OutputStream;
+import java.time.Instant;
/**
* Serializer using a Jackson {@link ObjectMapper}.
@@ -43,14 +44,28 @@ public class JacksonSerializer extends AbstractSerializer {
MODULE = module;
}
+ // Registered only on JJWT's default ObjectMapper, and intentionally not part of MODULE, so that it never
+ // overrides java.time handling (e.g. jackson-datatype-jsr310) configured on an application-provided ObjectMapper:
+ static final String DEFAULTS_MODULE_ID = "jjwt-jackson-defaults";
+ static final Module DEFAULTS_MODULE;
+
+ static {
+ SimpleModule module = new SimpleModule(DEFAULTS_MODULE_ID);
+ module.addSerializer(JacksonInstantSerializer.INSTANCE);
+ module.addDeserializer(Instant.class, JacksonInstantDeserializer.INSTANCE);
+ DEFAULTS_MODULE = module;
+ }
+
static final ObjectMapper DEFAULT_OBJECT_MAPPER = newObjectMapper();
/**
- * Creates and returns a new ObjectMapper with the {@code jjwt-jackson} module registered and
+ * Creates and returns a new ObjectMapper with the {@code jjwt-jackson} module registered, {@code java.time.Instant}
+ * values (de)serialized as ISO-8601 strings, and
* {@code JsonParser.Feature.STRICT_DUPLICATE_DETECTION} enabled (set to true) and
* {@code DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES} disabled (set to false).
*
- * @return a new ObjectMapper with the {@code jjwt-jackson} module registered and
+ * @return a new ObjectMapper with the {@code jjwt-jackson} module registered, {@code java.time.Instant}
+ * values (de)serialized as ISO-8601 strings, and
* {@code JsonParser.Feature.STRICT_DUPLICATE_DETECTION} enabled (set to true) and
* {@code DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES} disabled (set to false).
*
@@ -60,6 +75,7 @@ public class JacksonSerializer extends AbstractSerializer {
static ObjectMapper newObjectMapper() {
return new ObjectMapper()
.registerModule(MODULE)
+ .registerModule(DEFAULTS_MODULE)
.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true) // https://github.com/jwtk/jjwt/issues/877
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // https://github.com/jwtk/jjwt/issues/893
}
diff --git a/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonDeserializerTest.groovy b/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonDeserializerTest.groovy
index aba1f921a..60a1560d7 100644
--- a/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonDeserializerTest.groovy
+++ b/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonDeserializerTest.groovy
@@ -26,6 +26,8 @@ import io.jsonwebtoken.lang.Maps
import org.junit.Before
import org.junit.Test
+import java.time.Instant
+
import static org.junit.Assert.*
class JacksonDeserializerTest {
@@ -259,4 +261,46 @@ class JacksonDeserializerTest {
private static String base64(String input) {
return Encoders.BASE64.encode(input.getBytes('UTF-8'))
}
+
+ @Test
+ void testDeserializeInstantClaimTypeFromIso8601String() {
+ def result = new JacksonDeserializer(Maps.of("custom", Instant).build())
+ .deserialize(new StringReader('{"custom":"2026-10-03T10:00:00.123Z"}'))
+ assertEquals Instant.parse('2026-10-03T10:00:00.123Z'), result.custom
+ }
+
+ @Test
+ void testDeserializeInstantClaimTypeFromMillis() {
+ def result = new JacksonDeserializer(Maps.of("custom", Instant).build())
+ .deserialize(new StringReader('{"custom":1791021600123}'))
+ assertEquals Instant.ofEpochMilli(1791021600123L), result.custom
+ }
+
+ @Test
+ void testDeserializeInstantClaimTypeFromNull() {
+ def result = new JacksonDeserializer(Maps.of("custom", Instant).build())
+ .deserialize(new StringReader('{"custom":null}'))
+ assertNull result.custom
+ }
+
+ @Test
+ void testDeserializeInstantClaimTypeFromInvalidString() {
+ try {
+ new JacksonDeserializer(Maps.of("custom", Instant).build())
+ .deserialize(new StringReader('{"custom":"hello"}'))
+ fail()
+ } catch (DeserializationException expected) {
+ assertTrue expected.getMessage().contains('not an ISO-8601-formatted string')
+ }
+ }
+
+ @Test
+ void testDeserializeInstantClaimTypeFromUnexpectedToken() {
+ try {
+ new JacksonDeserializer(Maps.of("custom", Instant).build())
+ .deserialize(new StringReader('{"custom":true}'))
+ fail()
+ } catch (DeserializationException expected) {
+ }
+ }
}
diff --git a/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonSerializerTest.groovy b/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonSerializerTest.groovy
index 0b620ae53..259f9b1bb 100644
--- a/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonSerializerTest.groovy
+++ b/extensions/jackson/src/test/groovy/io/jsonwebtoken/jackson/io/JacksonSerializerTest.groovy
@@ -21,6 +21,16 @@ import io.jsonwebtoken.lang.Strings
import org.junit.Before
import org.junit.Test
+import com.fasterxml.jackson.core.JsonGenerator
+
+import com.fasterxml.jackson.databind.SerializerProvider
+
+import com.fasterxml.jackson.databind.module.SimpleModule
+
+import com.fasterxml.jackson.databind.ser.std.StdSerializer
+
+import java.time.Instant
+
import static org.easymock.EasyMock.*
import static org.junit.Assert.*
@@ -118,4 +128,25 @@ class JacksonSerializerTest {
byte[] result = serialize([hello: '世界'])
assertArrayEquals expected, result
}
+
+ @Test
+ void testInstantWithDefaultObjectMapper() {
+ def instant = Instant.parse('2026-10-03T10:00:00.123Z')
+ assertEquals '{"custom":"2026-10-03T10:00:00.123Z"}', Strings.utf8(serialize([custom: instant]))
+ }
+
+ @Test
+ void testInstantDoesNotOverrideApplicationObjectMapperConfig() {
+ // An application-provided ObjectMapper's java.time handling (e.g. jackson-datatype-jsr310) must be retained:
+ def module = new SimpleModule()
+ module.addSerializer(Instant, new StdSerializer(Instant) {
+ @Override
+ void serialize(Instant value, JsonGenerator gen, SerializerProvider provider) throws IOException {
+ gen.writeNumber(value.getEpochSecond())
+ }
+ })
+ ser = new JacksonSerializer(new ObjectMapper().registerModule(module))
+ def instant = Instant.parse('2026-10-03T10:00:00.123Z')
+ assertEquals '{"custom":1791021600}', Strings.utf8(serialize([custom: instant]))
+ }
}
diff --git a/extensions/orgjson/src/main/java/io/jsonwebtoken/orgjson/io/OrgJsonSerializer.java b/extensions/orgjson/src/main/java/io/jsonwebtoken/orgjson/io/OrgJsonSerializer.java
index da27e5a57..2733dd185 100644
--- a/extensions/orgjson/src/main/java/io/jsonwebtoken/orgjson/io/OrgJsonSerializer.java
+++ b/extensions/orgjson/src/main/java/io/jsonwebtoken/orgjson/io/OrgJsonSerializer.java
@@ -30,6 +30,7 @@
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.time.Instant;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
@@ -94,12 +95,15 @@ private Object toJSONInstance(Object object) throws IOException {
}
if (object instanceof Calendar) {
- object = ((Calendar) object).getTime(); //sets object to date, will be converted in next if-statement:
+ object = ((Calendar) object).toInstant(); //sets object to instant, will be converted in next if-statement:
}
if (object instanceof Date) {
- Date date = (Date) object;
- return DateFormats.formatIso8601(date);
+ object = ((Date) object).toInstant(); //sets object to instant, will be converted in next if-statement:
+ }
+
+ if (object instanceof Instant) {
+ return DateFormats.formatIso8601((Instant) object);
}
if (object instanceof byte[]) {
diff --git a/extensions/orgjson/src/test/groovy/io/jsonwebtoken/orgjson/io/OrgJsonSerializerTest.groovy b/extensions/orgjson/src/test/groovy/io/jsonwebtoken/orgjson/io/OrgJsonSerializerTest.groovy
index e8e5dcdf9..f4be50927 100644
--- a/extensions/orgjson/src/test/groovy/io/jsonwebtoken/orgjson/io/OrgJsonSerializerTest.groovy
+++ b/extensions/orgjson/src/test/groovy/io/jsonwebtoken/orgjson/io/OrgJsonSerializerTest.groovy
@@ -27,6 +27,8 @@ import org.json.JSONString
import org.junit.Before
import org.junit.Test
+import java.time.Instant
+
import static org.junit.Assert.*
class OrgJsonSerializerTest {
@@ -197,6 +199,12 @@ class OrgJsonSerializerTest {
assertEquals "\"$formatted\"" as String, ser(now)
}
+ @Test
+ void testInstant() {
+ def instant = Instant.parse('2026-10-03T10:00:00.123Z')
+ assertEquals '"2026-10-03T10:00:00.123Z"', ser(instant)
+ }
+
@Test
void testCalendar() {
def cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/DefaultClaims.java b/impl/src/main/java/io/jsonwebtoken/impl/DefaultClaims.java
index 70a6a5a42..ae16421a1 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/DefaultClaims.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/DefaultClaims.java
@@ -18,11 +18,13 @@
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.RequiredTypeException;
import io.jsonwebtoken.impl.lang.JwtDateConverter;
+import io.jsonwebtoken.impl.lang.JwtInstantConverter;
import io.jsonwebtoken.impl.lang.Parameter;
import io.jsonwebtoken.impl.lang.Parameters;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.lang.Registry;
+import java.time.Instant;
import java.util.Date;
import java.util.Map;
import java.util.Set;
@@ -30,8 +32,8 @@
public class DefaultClaims extends ParameterMap implements Claims {
private static final String CONVERSION_ERROR_MSG = "Cannot convert existing claim value of type '%s' to desired type " +
- "'%s'. JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. " +
- "Anything more complex is expected to be already converted to your desired type by the JSON Deserializer " +
+ "'%s'. JJWT only converts simple String, Date, Instant, Long, Integer, Short and Byte types " +
+ "automatically. Anything more complex is expected to be already converted to your desired type by the JSON Deserializer " +
"implementation. You may specify a custom Deserializer for a JwtParser with the desired conversion " +
"configuration via the JwtParserBuilder.deserializer() method. " +
"See https://github.com/jwtk/jjwt#custom-json-processor for more information. If using Jackson, you can " +
@@ -40,9 +42,9 @@ public class DefaultClaims extends ParameterMap implements Claims {
static final Parameter ISSUER = Parameters.string(Claims.ISSUER, "Issuer");
static final Parameter SUBJECT = Parameters.string(Claims.SUBJECT, "Subject");
static final Parameter> AUDIENCE = Parameters.stringSet(Claims.AUDIENCE, "Audience");
- static final Parameter EXPIRATION = Parameters.rfcDate(Claims.EXPIRATION, "Expiration Time");
- static final Parameter NOT_BEFORE = Parameters.rfcDate(Claims.NOT_BEFORE, "Not Before");
- static final Parameter ISSUED_AT = Parameters.rfcDate(Claims.ISSUED_AT, "Issued At");
+ static final Parameter EXPIRATION = Parameters.rfc(Claims.EXPIRATION, "Expiration Time");
+ static final Parameter NOT_BEFORE = Parameters.rfc(Claims.NOT_BEFORE, "Not Before");
+ static final Parameter ISSUED_AT = Parameters.rfc(Claims.ISSUED_AT, "Issued At");
static final Parameter JTI = Parameters.string(Claims.ID, "JWT ID");
static final Registry> PARAMS =
@@ -80,21 +82,46 @@ public Set getAudience() {
return get(AUDIENCE);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public Date getExpiration() {
+ return toDate(expiration());
+ }
+
+ @Override
+ public Instant expiration() {
return get(EXPIRATION);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public Date getNotBefore() {
+ return toDate(notBefore());
+ }
+
+ @Override
+ public Instant notBefore() {
return get(NOT_BEFORE);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public Date getIssuedAt() {
+ return toDate(issuedAt());
+ }
+
+ @Override
+ public Instant issuedAt() {
return get(ISSUED_AT);
}
+ private static Date toDate(Instant instant) {
+ return instant != null ? Date.from(instant) : null;
+ }
+
@Override
public String getId() {
return get(JTI);
@@ -108,6 +135,11 @@ public T get(String claimName, Class requiredType) {
if (requiredType.isInstance(value)) {
return requiredType.cast(value);
}
+ // exp, nbf and iat are idiomatically represented as Instant; convert directly instead of re-parsing the raw
+ // (seconds) value below, which would otherwise be interpreted as milliseconds:
+ if (value instanceof Instant && Date.class.equals(requiredType)) {
+ return requiredType.cast(Date.from((Instant) value));
+ }
value = get(claimName);
if (value == null) {
@@ -121,6 +153,13 @@ public T get(String claimName, Class requiredType) {
String msg = "Cannot create Date from '" + claimName + "' value '" + value + "'. Cause: " + e.getMessage();
throw new IllegalArgumentException(msg, e);
}
+ } else if (Instant.class.equals(requiredType)) {
+ try {
+ value = JwtInstantConverter.toInstant(value); // NOT specInstant logic
+ } catch (Exception e) {
+ String msg = "Cannot create Instant from '" + claimName + "' value '" + value + "'. Cause: " + e.getMessage();
+ throw new IllegalArgumentException(msg, e);
+ }
}
return castClaimValue(claimName, value, requiredType);
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/DefaultClock.java b/impl/src/main/java/io/jsonwebtoken/impl/DefaultClock.java
index bd9d4ecbc..fb49164a8 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/DefaultClock.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/DefaultClock.java
@@ -17,6 +17,7 @@
import io.jsonwebtoken.Clock;
+import java.time.Instant;
import java.util.Date;
/**
@@ -32,12 +33,27 @@ public class DefaultClock implements Clock {
public static final Clock INSTANCE = new DefaultClock();
/**
- * Simply returns new {@link Date}().
+ * Simply returns {@link Instant#now()}.
+ *
+ * @return the current instant.
+ * @since 0.14.0
+ */
+ @Override
+ public Instant instant() {
+ return Instant.now();
+ }
+
+ /**
+ * Returns the current {@link #instant()} as a new {@link Date} instance.
*
* @return a new {@link Date} instance.
+ * @deprecated since 0.14.0 in favor of {@link #instant()}. This method will be removed before the
+ * JJWT 1.0 release.
*/
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public Date now() {
- return new Date();
+ return Date.from(instant());
}
}
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtBuilder.java b/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtBuilder.java
index 56706ba30..4f2152758 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtBuilder.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtBuilder.java
@@ -72,6 +72,7 @@
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
+import java.time.Instant;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Map;
@@ -427,33 +428,60 @@ public AudienceCollection audience() {
return new DelegateAudienceCollection<>(this, claims().audience());
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtBuilder setExpiration(Date exp) {
return expiration(exp);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtBuilder expiration(Date exp) {
+ return expiration(exp != null ? exp.toInstant() : null);
+ }
+
+ @Override
+ public JwtBuilder expiration(Instant exp) {
return claims().expiration(exp).and();
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtBuilder setNotBefore(Date nbf) {
return notBefore(nbf);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtBuilder notBefore(Date nbf) {
+ return notBefore(nbf != null ? nbf.toInstant() : null);
+ }
+
+ @Override
+ public JwtBuilder notBefore(Instant nbf) {
return claims().notBefore(nbf).and();
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtBuilder setIssuedAt(Date iat) {
return issuedAt(iat);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtBuilder issuedAt(Date iat) {
+ return issuedAt(iat != null ? iat.toInstant() : null);
+ }
+
+ @Override
+ public JwtBuilder issuedAt(Instant iat) {
return claims().issuedAt(iat).and();
}
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java b/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java
index d9a61f4dc..250629418 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java
@@ -84,6 +84,9 @@
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
@@ -667,21 +670,20 @@ private byte[] verifySignature(final TokenizedJwt tokenized, final JwsHeader jws
//since 0.3:
if (claims != null) {
- final Date now = this.clock.now();
- long nowTime = now.getTime();
+ // truncate to millis: clock skew and error messages are expressed in milliseconds:
+ final Instant now = this.clock.instant().truncatedTo(ChronoUnit.MILLIS);
// https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.4
// token MUST NOT be accepted on or after any specified exp time:
- Date exp = claims.getExpiration();
+ Instant exp = claims.expiration();
if (exp != null) {
- long maxTime = nowTime - this.allowedClockSkewMillis;
- Date max = allowSkew ? new Date(maxTime) : now;
- if (max.after(exp)) {
+ Instant max = allowSkew ? now.minusMillis(this.allowedClockSkewMillis) : now;
+ if (max.isAfter(exp)) {
String expVal = DateFormats.formatIso8601(exp, true);
String nowVal = DateFormats.formatIso8601(now, true);
- long differenceMillis = nowTime - exp.getTime();
+ long differenceMillis = millisBetween(exp, now);
String msg = "JWT expired " + differenceMillis + " milliseconds ago at " + expVal + ". " +
"Current time: " + nowVal + ". Allowed clock skew: " +
@@ -692,16 +694,15 @@ private byte[] verifySignature(final TokenizedJwt tokenized, final JwsHeader jws
// https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.5
// token MUST NOT be accepted before any specified nbf time:
- Date nbf = claims.getNotBefore();
+ Instant nbf = claims.notBefore();
if (nbf != null) {
- long minTime = nowTime + this.allowedClockSkewMillis;
- Date min = allowSkew ? new Date(minTime) : now;
- if (min.before(nbf)) {
+ Instant min = allowSkew ? now.plusMillis(this.allowedClockSkewMillis) : now;
+ if (min.isBefore(nbf)) {
String nbfVal = DateFormats.formatIso8601(nbf, true);
String nowVal = DateFormats.formatIso8601(now, true);
- long differenceMillis = nbf.getTime() - nowTime;
+ long differenceMillis = millisBetween(now, nbf);
String msg = "JWT early by " + differenceMillis + " milliseconds before " + nbfVal +
". Current time: " + nowVal + ". Allowed clock skew: " +
@@ -726,6 +727,18 @@ private static Object normalize(Object o) {
return o;
}
+ /**
+ * Returns the number of milliseconds from {@code start} to {@code end}, saturating at
+ * {@link Long#MAX_VALUE} if the difference cannot be represented as a {@code long}.
+ */
+ private static long millisBetween(Instant start, Instant end) {
+ try {
+ return Duration.between(start, end).toMillis();
+ } catch (ArithmeticException e) {
+ return Long.MAX_VALUE;
+ }
+ }
+
private void validateExpectedClaims(Header header, Claims claims) {
final Claims expected = expectedClaims.build();
@@ -743,6 +756,15 @@ private void validateExpectedClaims(Header header, Claims claims) {
"cannot be converted to a Date using current heuristics. Value: " + actualClaimValue;
throw new IncorrectClaimException(header, claims, expectedClaimName, expectedClaimValue, msg);
}
+ } else if (expectedClaimValue instanceof Instant) {
+ try {
+ actualClaimValue = claims.get(expectedClaimName, Instant.class);
+ } catch (Exception e) {
+ String msg = "JWT Claim '" + expectedClaimName + "' was expected to be an Instant, but its " +
+ "value cannot be converted to an Instant using current heuristics. Value: " +
+ actualClaimValue;
+ throw new IncorrectClaimException(header, claims, expectedClaimName, expectedClaimValue, msg);
+ }
}
if (actualClaimValue == null) {
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParserBuilder.java b/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParserBuilder.java
index c12b1054b..02ec47eca 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParserBuilder.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParserBuilder.java
@@ -53,6 +53,7 @@
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
+import java.time.Instant;
import java.util.Date;
import java.util.Map;
import java.util.Set;
@@ -155,15 +156,22 @@ public JwtParserBuilder b64Url(Decoder decoder) {
return this;
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtParserBuilder requireIssuedAt(Date issuedAt) {
- expectedClaims.setIssuedAt(issuedAt);
+ return requireIssuedAt(toInstant(issuedAt));
+ }
+
+ @Override
+ public JwtParserBuilder requireIssuedAt(Instant issuedAt) {
+ expectedClaims.issuedAt(issuedAt);
return this;
}
@Override
public JwtParserBuilder requireIssuer(String issuer) {
- expectedClaims.setIssuer(issuer);
+ expectedClaims.issuer(issuer);
return this;
}
@@ -175,28 +183,46 @@ public JwtParserBuilder requireAudience(String audience) {
@Override
public JwtParserBuilder requireSubject(String subject) {
- expectedClaims.setSubject(subject);
+ expectedClaims.subject(subject);
return this;
}
@Override
public JwtParserBuilder requireId(String id) {
- expectedClaims.setId(id);
+ expectedClaims.id(id);
return this;
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtParserBuilder requireExpiration(Date expiration) {
- expectedClaims.setExpiration(expiration);
+ return requireExpiration(toInstant(expiration));
+ }
+
+ @Override
+ public JwtParserBuilder requireExpiration(Instant expiration) {
+ expectedClaims.expiration(expiration);
return this;
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public JwtParserBuilder requireNotBefore(Date notBefore) {
- expectedClaims.setNotBefore(notBefore);
+ return requireNotBefore(toInstant(notBefore));
+ }
+
+ @Override
+ public JwtParserBuilder requireNotBefore(Instant notBefore) {
+ expectedClaims.notBefore(notBefore);
return this;
}
+ private static Instant toInstant(Date date) {
+ return date != null ? date.toInstant() : null;
+ }
+
@Override
public JwtParserBuilder require(String claimName, Object value) {
Assert.hasText(claimName, "claim name cannot be null or empty.");
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/DelegatingClaimsMutator.java b/impl/src/main/java/io/jsonwebtoken/impl/DelegatingClaimsMutator.java
index fd5c48330..fb1f673c8 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/DelegatingClaimsMutator.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/DelegatingClaimsMutator.java
@@ -23,6 +23,7 @@
import io.jsonwebtoken.lang.MapMutator;
import io.jsonwebtoken.lang.Strings;
+import java.time.Instant;
import java.util.Date;
import java.util.Map;
import java.util.Set;
@@ -140,36 +141,67 @@ protected void changed() {
};
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public T setExpiration(Date exp) {
return expiration(exp);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public T expiration(Date exp) {
+ return expiration(toInstant(exp));
+ }
+
+ @Override
+ public T expiration(Instant exp) {
return put(DefaultClaims.EXPIRATION, exp);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public T setNotBefore(Date nbf) {
return notBefore(nbf);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public T notBefore(Date nbf) {
+ return notBefore(toInstant(nbf));
+ }
+
+ @Override
+ public T notBefore(Instant nbf) {
return put(DefaultClaims.NOT_BEFORE, nbf);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public T setIssuedAt(Date iat) {
return issuedAt(iat);
}
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public T issuedAt(Date iat) {
+ return issuedAt(toInstant(iat));
+ }
+
+ @Override
+ public T issuedAt(Instant iat) {
return put(DefaultClaims.ISSUED_AT, iat);
}
+ private static Instant toInstant(Date date) {
+ return date != null ? date.toInstant() : null;
+ }
+
@Override
public T setId(String jti) {
return id(jti);
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/FixedClock.java b/impl/src/main/java/io/jsonwebtoken/impl/FixedClock.java
index cecae75ee..238415461 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/FixedClock.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/FixedClock.java
@@ -17,6 +17,7 @@
import io.jsonwebtoken.Clock;
+import java.time.Instant;
import java.util.Date;
/**
@@ -27,38 +28,67 @@
*/
public class FixedClock implements Clock {
- private final Date now;
+ private final Instant instant;
/**
- * Creates a new fixed clock using new {@link Date Date}() as the seed timestamp. All calls to
- * {@link #now now()} will always return this seed Date.
+ * Creates a new fixed clock using {@link Instant#now()} as the seed timestamp. All calls to
+ * {@link #instant instant()} will always return this seed Instant.
*/
public FixedClock() {
- this(new Date());
+ this(Instant.now());
}
/**
* Creates a new fixed clock using the specified seed timestamp. All calls to
- * {@link #now now()} will always return this seed Date.
+ * {@link #instant instant()} will always return this seed Instant.
+ *
+ * @param instant the specified Instant to always return from all calls to {@link #instant instant()}.
+ * @since 0.14.0
+ */
+ public FixedClock(Instant instant) {
+ this.instant = instant;
+ }
+
+ /**
+ * Creates a new fixed clock using the specified seed timestamp. All calls to
+ * {@link #instant instant()} will always return this seed timestamp.
*
* @param now the specified Date to always return from all calls to {@link #now now()}.
+ * @deprecated since 0.14.0 in favor of {@link #FixedClock(Instant)}. This constructor will be removed before
+ * the JJWT 1.0 release.
*/
+ @Deprecated
public FixedClock(Date now) {
- this.now = now;
+ this(now != null ? now.toInstant() : null);
}
/**
* Creates a new fixed clock using the specified seed timestamp. All calls to
- * {@link #now now()} will always return this seed Date.
+ * {@link #instant instant()} will always return this seed timestamp.
*
- * @param timeInMillis the specified Date in milliseconds to always return from all calls to {@link #now now()}.
+ * @param timeInMillis the specified timestamp in milliseconds to always return from all calls to
+ * {@link #instant instant()}.
*/
public FixedClock(long timeInMillis) {
- this(new Date(timeInMillis));
+ this(Instant.ofEpochMilli(timeInMillis));
}
+ @Override
+ public Instant instant() {
+ return this.instant;
+ }
+
+ /**
+ * Returns the seed timestamp as a new {@link Date} instance.
+ *
+ * @return the seed timestamp as a new {@link Date} instance, or {@code null} if the seed is {@code null}.
+ * @deprecated since 0.14.0 in favor of {@link #instant()}. This method will be removed before the
+ * JJWT 1.0 release.
+ */
+ @SuppressWarnings("deprecation")
+ @Deprecated
@Override
public Date now() {
- return this.now;
+ return this.instant != null ? Date.from(this.instant) : null;
}
}
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtDateConverter.java b/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtDateConverter.java
index 2dc15c251..dbe7e73cf 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtDateConverter.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtDateConverter.java
@@ -21,51 +21,18 @@
import java.util.Calendar;
import java.util.Date;
-public class JwtDateConverter implements Converter {
-
- public static final JwtDateConverter INSTANCE = new JwtDateConverter();
-
- @Override
- public Object applyTo(Date date) {
- if (date == null) {
- return null;
- }
- // https://www.rfc-editor.org/rfc/rfc7519.html#section-2, 'Numeric Date' definition:
- return date.getTime() / 1000L;
- }
-
- @Override
- public Date applyFrom(Object o) {
- return toSpecDate(o);
- }
+/**
+ * Converts object values to {@link Date} instances using heuristics. Retained only to support the deprecated
+ * {@code Claims.get(claimName, Date.class)} conversion, which (unlike {@link JwtInstantConverter}) parses ISO-8601
+ * strings leniently. RFC NumericDate claims ({@code exp}, {@code nbf} and {@code iat}) are converted by
+ * {@link JwtInstantConverter}.
+ *
+ * This class will be removed along with the deprecated {@code Date}-based APIs before the JJWT 1.0 release.
+ */
+public final class JwtDateConverter {
- /**
- * Returns an RFC-compatible {@link Date} equivalent of the specified object value using heuristics.
- *
- * @param value object to convert to a {@code Date} using heuristics.
- * @return an RFC-compatible {@link Date} equivalent of the specified object value using heuristics.
- * @since 0.10.0
- */
- public static Date toSpecDate(Object value) {
- if (value == null) {
- return null;
- }
- if (value instanceof String) {
- try {
- value = Long.parseLong((String) value);
- } catch (NumberFormatException ignored) { // will try in the fallback toDate method call below
- }
- }
- if (value instanceof Number) {
- // https://github.com/jwtk/jjwt/issues/122:
- // The JWT RFC *mandates* NumericDate values are represented as seconds.
- // Because java.util.Date requires milliseconds, we need to multiply by 1000:
- long seconds = ((Number) value).longValue();
- value = seconds * 1000;
- }
- //v would have been normalized to milliseconds if it was a number value, so perform normal date conversion:
- return toDate(value);
- }
+ private JwtDateConverter() {
+ } // prevent instantiation
/**
* Returns a {@link Date} equivalent of the specified object value using heuristics.
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtInstantConverter.java b/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtInstantConverter.java
new file mode 100644
index 000000000..78fd5e4cc
--- /dev/null
+++ b/impl/src/main/java/io/jsonwebtoken/impl/lang/JwtInstantConverter.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.impl.lang;
+
+import io.jsonwebtoken.lang.DateFormats;
+
+import java.text.ParseException;
+import java.time.DateTimeException;
+import java.time.Instant;
+import java.util.Calendar;
+import java.util.Date;
+
+/**
+ * Converts between {@link Instant} values and their RFC 7519
+ * NumericDate representation (seconds since
+ * the epoch).
+ *
+ * @since 0.14.0
+ */
+public class JwtInstantConverter implements Converter {
+
+ public static final JwtInstantConverter INSTANCE = new JwtInstantConverter();
+
+ @Override
+ public Object applyTo(Instant instant) {
+ if (instant == null) {
+ return null;
+ }
+ // https://www.rfc-editor.org/rfc/rfc7519.html#section-2, 'Numeric Date' definition:
+ return instant.getEpochSecond();
+ }
+
+ @Override
+ public Instant applyFrom(Object o) {
+ return toSpecInstant(o);
+ }
+
+ /**
+ * Returns an RFC-compatible {@link Instant} equivalent of the specified object value using heuristics. Numeric
+ * values (and numeric strings) are interpreted as seconds since the epoch, as mandated by the JWT RFC.
+ *
+ * @param value object to convert to an {@code Instant} using heuristics.
+ * @return an RFC-compatible {@link Instant} equivalent of the specified object value using heuristics.
+ * @throws IllegalArgumentException if the value cannot be converted or is out of the supported range.
+ */
+ public static Instant toSpecInstant(Object value) throws IllegalArgumentException {
+ if (value == null) {
+ return null;
+ }
+ if (value instanceof String) {
+ try {
+ value = Long.parseLong((String) value);
+ } catch (NumberFormatException ignored) { // will try in the fallback toInstant method call below
+ }
+ }
+ if (value instanceof Number) {
+ // https://github.com/jwtk/jjwt/issues/122:
+ // The JWT RFC *mandates* NumericDate values are represented as seconds:
+ long seconds = ((Number) value).longValue();
+ try {
+ return Instant.ofEpochSecond(seconds);
+ } catch (DateTimeException e) {
+ throw outOfRange(value, e);
+ }
+ }
+ return toInstant(value);
+ }
+
+ /**
+ * Returns an {@link Instant} equivalent of the specified object value using heuristics. Unlike
+ * {@link #toSpecInstant(Object)}, numeric values are interpreted as milliseconds since the epoch.
+ *
+ * @param v the object value to represent as an Instant.
+ * @return an {@link Instant} equivalent of the specified object value using heuristics.
+ * @throws IllegalArgumentException if the value cannot be converted or is out of the supported range.
+ */
+ public static Instant toInstant(Object v) throws IllegalArgumentException {
+ if (v == null) {
+ return null;
+ } else if (v instanceof Instant) {
+ return (Instant) v;
+ } else if (v instanceof Date) {
+ return ((Date) v).toInstant();
+ } else if (v instanceof Calendar) {
+ return ((Calendar) v).toInstant();
+ } else if (v instanceof Number) {
+ //assume millis:
+ long millis = ((Number) v).longValue();
+ try {
+ return Instant.ofEpochMilli(millis);
+ } catch (DateTimeException e) {
+ throw outOfRange(v, e);
+ }
+ } else if (v instanceof String) {
+ return parseIso8601Instant((String) v);
+ } else {
+ String msg = "Cannot create Instant from object of type " + v.getClass().getName() + ".";
+ throw new IllegalArgumentException(msg);
+ }
+ }
+
+ private static IllegalArgumentException outOfRange(Object value, Exception cause) {
+ String msg = "Value '" + value + "' is outside the supported Instant range. Cause: " + cause.getMessage();
+ return new IllegalArgumentException(msg, cause);
+ }
+
+ /**
+ * Parses the specified ISO-8601-formatted string and returns the corresponding {@link Instant} instance.
+ *
+ * @param value an ISO-8601-formatted string.
+ * @return an {@link Instant} instance reflecting the specified ISO-8601-formatted string.
+ */
+ private static Instant parseIso8601Instant(String value) throws IllegalArgumentException {
+ try {
+ return DateFormats.parseIso8601Instant(value);
+ } catch (ParseException e) {
+ String msg = "String value is not a JWT NumericDate, nor is it ISO-8601-formatted. " +
+ "All heuristics exhausted. Cause: " + e.getMessage();
+ throw new IllegalArgumentException(msg, e);
+ }
+ }
+}
diff --git a/impl/src/main/java/io/jsonwebtoken/impl/lang/Parameters.java b/impl/src/main/java/io/jsonwebtoken/impl/lang/Parameters.java
index 36db08193..d3b5cc37c 100644
--- a/impl/src/main/java/io/jsonwebtoken/impl/lang/Parameters.java
+++ b/impl/src/main/java/io/jsonwebtoken/impl/lang/Parameters.java
@@ -24,8 +24,8 @@
import java.net.URI;
import java.security.MessageDigest;
import java.security.cert.X509Certificate;
+import java.time.Instant;
import java.util.Collection;
-import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -41,8 +41,8 @@ public static Parameter string(String id, String name) {
return builder(String.class).setId(id).setName(name).build();
}
- public static Parameter rfcDate(String id, String name) {
- return builder(Date.class).setConverter(JwtDateConverter.INSTANCE).setId(id).setName(name).build();
+ public static Parameter rfc(String id, String name) {
+ return builder(Instant.class).setConverter(JwtInstantConverter.INSTANCE).setId(id).setName(name).build();
}
public static Parameter> x509Chain(String id, String name) {
diff --git a/impl/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy
index d6c1cf9ec..d1db93021 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy
@@ -18,7 +18,6 @@ package io.jsonwebtoken
import io.jsonwebtoken.impl.DefaultJwtParser
import io.jsonwebtoken.impl.FixedClock
import io.jsonwebtoken.impl.JwtTokenizer
-import io.jsonwebtoken.impl.lang.JwtDateConverter
import io.jsonwebtoken.impl.security.TestKeys
import io.jsonwebtoken.io.Encoders
import io.jsonwebtoken.lang.DateFormats
@@ -30,6 +29,8 @@ import org.junit.Test
import javax.crypto.SecretKey
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
+import java.time.Instant
+import java.time.temporal.ChronoUnit
import static io.jsonwebtoken.DateTestUtils.truncateMillis
import static io.jsonwebtoken.impl.DefaultJwtParser.INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE
@@ -251,8 +252,8 @@ class JwtParserTest {
void testParseWithPrematureJwt() {
long differenceMillis = 100000 // arbitrary, anything > 0 is fine
- def nbf = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def earlier = new Date(nbf.getTime() - differenceMillis)
+ def nbf = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def earlier = nbf.minusMillis(differenceMillis)
String compact = Jwts.builder().subject('Joe').notBefore(nbf).compact()
@@ -276,13 +277,10 @@ class JwtParserTest {
void testParseWithExpiredJwtWithinAllowedClockSkew() {
long differenceMillis = 3000 // arbitrary, anything > 0 is fine
- long millis = System.currentTimeMillis()
// RFC requires time in seconds, so we need to base our assertions based on second-normalized dates,
// otherwise we'll get nondeterministic tests:
- long seconds = (millis / 1000L).longValue()
- millis = seconds * 1000L
- def exp = new Date(millis)
- def later = new Date(exp.getTime() + differenceMillis)
+ def exp = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def later = exp.plusMillis(differenceMillis)
def s = Jwts.builder().expiration(exp).compact()
String subject = 'Joe'
@@ -298,8 +296,8 @@ class JwtParserTest {
void testParseWithExpiredJwtNotWithinAllowedClockSkew() {
long differenceMillis = 3000 // arbitrary, anything > 0 is fine
- def exp = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def later = new Date(exp.getTime() + differenceMillis)
+ def exp = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def later = exp.plusMillis(differenceMillis)
def s = Jwts.builder().expiration(exp).compact()
@@ -334,8 +332,8 @@ class JwtParserTest {
void testParseWithPrematureJwtNotWithinAllowedClockSkew() {
long differenceMillis = 3000 // arbitrary, anything > 0 is fine
- def nbf = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def earlier = new Date(nbf.getTime() - differenceMillis)
+ def nbf = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def earlier = nbf.minusMillis(differenceMillis)
String compact = Jwts.builder().subject('Joe').notBefore(nbf).compact()
@@ -567,8 +565,8 @@ class JwtParserTest {
void testParseSignedClaimsWithExpiredJws() {
long differenceMillis = 843 // arbitrary, anything > 0 is fine
- def exp = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def later = new Date(exp.getTime() + differenceMillis)
+ def exp = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def later = exp.plusMillis(differenceMillis)
String sub = 'Joe'
byte[] key = randomKey()
@@ -592,8 +590,8 @@ class JwtParserTest {
void testParseSignedClaimsWithPrematureJws() {
long differenceMillis = 3842 // arbitrary, anything > 0 is fine
- def nbf = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def earlier = new Date(nbf.getTime() - differenceMillis)
+ def nbf = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def earlier = nbf.minusMillis(differenceMillis)
String sub = 'Joe'
byte[] key = randomKey()
@@ -1462,6 +1460,184 @@ class JwtParserTest {
parseSignedClaims(compact)
}
+ @Test
+ void testParseRequireIssuedAtInstant_Success() {
+ def issuedAt = Instant.now()
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).issuedAt(issuedAt).compact()
+
+ Jwt jwt = Jwts.parser().setSigningKey(key).requireIssuedAt(issuedAt).build()
+ .parseSignedClaims(compact)
+
+ assertEquals issuedAt.truncatedTo(ChronoUnit.SECONDS), jwt.getPayload().issuedAt()
+ }
+
+ @Test(expected = IncorrectClaimException)
+ void testParseRequireIssuedAtInstant_Incorrect_Fail() {
+ def now = Instant.now()
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).issuedAt(now.minusSeconds(10))
+ .compact()
+
+ Jwts.parser().setSigningKey(key).requireIssuedAt(now).build().parseSignedClaims(compact)
+ }
+
+ @Test(expected = MissingClaimException)
+ void testParseRequireIssuedAtInstant_Missing_Fail() {
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).subject("Dummy").compact()
+
+ Jwts.parser().setSigningKey(key).requireIssuedAt(Instant.now()).build().parseSignedClaims(compact)
+ }
+
+ @Test
+ void testParseRequireExpirationInstant_Success() {
+ def expiration = Instant.now().plusSeconds(10)
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).expiration(expiration).compact()
+
+ Jwt jwt = Jwts.parser().setSigningKey(key).requireExpiration(expiration).build()
+ .parseSignedClaims(compact)
+
+ assertEquals expiration.truncatedTo(ChronoUnit.SECONDS), jwt.getPayload().expiration()
+ }
+
+ @Test(expected = IncorrectClaimException)
+ void testParseRequireExpirationInstant_Incorrect_Fail() {
+ def now = Instant.now()
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).expiration(now.plusSeconds(10))
+ .compact()
+
+ Jwts.parser().setSigningKey(key).requireExpiration(now.plusSeconds(20)).build().parseSignedClaims(compact)
+ }
+
+ @Test(expected = MissingClaimException)
+ void testParseRequireExpirationInstant_Missing_Fail() {
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).subject("Dummy").compact()
+
+ Jwts.parser().setSigningKey(key).requireExpiration(Instant.now().plusSeconds(10)).build()
+ .parseSignedClaims(compact)
+ }
+
+ @Test
+ void testParseRequireNotBeforeInstant_Success() {
+ def notBefore = Instant.now().minusSeconds(10)
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).notBefore(notBefore).compact()
+
+ Jwt jwt = Jwts.parser().setSigningKey(key).requireNotBefore(notBefore).build()
+ .parseSignedClaims(compact)
+
+ assertEquals notBefore.truncatedTo(ChronoUnit.SECONDS), jwt.getPayload().notBefore()
+ }
+
+ @Test(expected = IncorrectClaimException)
+ void testParseRequireNotBeforeInstant_Incorrect_Fail() {
+ def now = Instant.now()
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).notBefore(now.minusSeconds(10))
+ .compact()
+
+ Jwts.parser().setSigningKey(key).requireNotBefore(now.minusSeconds(20)).build().parseSignedClaims(compact)
+ }
+
+ @Test(expected = MissingClaimException)
+ void testParseRequireNotBeforeInstant_Missing_Fail() {
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).subject("Dummy").compact()
+
+ Jwts.parser().setSigningKey(key).requireNotBefore(Instant.now().minusSeconds(10)).build()
+ .parseSignedClaims(compact)
+ }
+
+ @Test
+ void testParseRequireExpirationDateMatchesInstant() {
+ // token built with the Instant API must satisfy a requirement expressed with the deprecated Date API:
+ def expiration = Instant.now().plusSeconds(10)
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).expiration(expiration).compact()
+
+ Jwt jwt = Jwts.parser().setSigningKey(key).requireExpiration(Date.from(expiration)).build()
+ .parseSignedClaims(compact)
+
+ assertEquals Date.from(expiration.truncatedTo(ChronoUnit.SECONDS)), jwt.getPayload().getExpiration()
+ }
+
+ @Test
+ void testParseRequireCustomInstant_Success() {
+ def anInstant = Instant.now().truncatedTo(ChronoUnit.MILLIS)
+ byte[] key = randomKey()
+ // custom claim value as an ISO-8601 string, as serialized for a Date:
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key)
+ .claim("anInstant", DateFormats.formatIso8601(anInstant)).compact()
+
+ Jwt jwt = Jwts.parser().setSigningKey(key).require("anInstant", anInstant).build()
+ .parseSignedClaims(compact)
+
+ assertEquals anInstant, jwt.getPayload().get("anInstant", Instant.class)
+ }
+
+ @Test
+ void testParseRequireCustomInstantFromMillis_Success() {
+ def anInstant = Instant.now().truncatedTo(ChronoUnit.MILLIS)
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key)
+ .claim("anInstant", anInstant.toEpochMilli()).compact()
+
+ Jwts.parser().setSigningKey(key).require("anInstant", anInstant).build().parseSignedClaims(compact)
+ }
+
+ @Test
+ void testParseRequireCustomInstantWhenClaimIsNotAnInstant() {
+ byte[] key = randomKey()
+ String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).claim("anInstant", 'hello').compact()
+
+ try {
+ Jwts.parser().setSigningKey(key).require("anInstant", Instant.now()).build().parseSignedClaims(compact)
+ fail()
+ } catch (IncorrectClaimException e) {
+ String expected = 'JWT Claim \'anInstant\' was expected to be an Instant, but its value cannot be ' +
+ 'converted to an Instant using current heuristics. Value: hello'
+ assertEquals expected, e.getMessage()
+ }
+ }
+
+ @Test
+ void testParseExpiredWithInstantOnlyClock() {
+ // the parser must only use Clock.instant(), never the deprecated Clock.now():
+ def fixed = Instant.parse('2026-10-03T10:00:00Z')
+ Clock clock = new Clock() {
+ @Override
+ Date now() {
+ throw new UnsupportedOperationException('now() should not be called')
+ }
+
+ @Override
+ Instant instant() {
+ return fixed
+ }
+ }
+ String compact = Jwts.builder().expiration(fixed.minusSeconds(1)).compact()
+
+ try {
+ Jwts.parser().unsecured().clock(clock).build().parse(compact)
+ fail()
+ } catch (ExpiredJwtException e) {
+ assertEquals 'JWT expired 1000 milliseconds ago at 2026-10-03T09:59:59.000Z. Current time: ' +
+ '2026-10-03T10:00:00.000Z. Allowed clock skew: 0 milliseconds.', e.getMessage()
+ }
+ }
+
+ @Test
+ void testParsePrematureWithMaxClockSkewDoesNotOverflow() {
+ // now + skew previously overflowed when computed with long millis, rejecting a token within the skew:
+ String compact = Jwts.builder().notBefore(Instant.now().plusSeconds(1000)).compact()
+
+ Jwts.parser().unsecured().setAllowedClockSkewSeconds(Long.MAX_VALUE.intdiv(1000L) as long).build().parse(compact)
+ }
+
@Test
void testParseRequireCustomDate_Success() {
diff --git a/impl/src/test/groovy/io/jsonwebtoken/JwtsTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/JwtsTest.groovy
index c232a1ade..dc8f131de 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/JwtsTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/JwtsTest.groovy
@@ -151,7 +151,7 @@ class JwtsTest {
} catch (MalformedJwtException e) {
String expected = 'Invalid claims: Invalid JWT Claims \'exp\' (Expiration Time) value: -42-. ' +
'String value is not a JWT NumericDate, nor is it ISO-8601-formatted. All heuristics exhausted. ' +
- 'Cause: Unparseable date: "-42-"'
+ 'Cause: Text \'-42-\' could not be parsed at index 1'
assertEquals expected, e.getMessage()
}
}
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClaimsTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClaimsTest.groovy
index ae987402d..5c95c82bc 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClaimsTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClaimsTest.groovy
@@ -344,7 +344,7 @@ class DefaultClaimsTest {
claims.put(param.getId(), val)
fail()
} catch (IllegalArgumentException iae) {
- String msg = "Invalid JWT Claims $param value: hi. Cannot create Date from object of type io.jsonwebtoken.impl.DefaultClaimsTest\$1."
+ String msg = "Invalid JWT Claims $param value: hi. Cannot create Instant from object of type io.jsonwebtoken.impl.DefaultClaimsTest\$1."
assertEquals msg, iae.getMessage()
}
}
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClockTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClockTest.groovy
new file mode 100644
index 000000000..87cbe065e
--- /dev/null
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultClockTest.groovy
@@ -0,0 +1,43 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.impl
+
+import org.junit.Test
+
+import java.time.Instant
+
+import static org.junit.Assert.*
+
+class DefaultClockTest {
+
+ @Test
+ void testInstant() {
+ def before = Instant.now()
+ def instant = DefaultClock.INSTANCE.instant()
+ def after = Instant.now()
+ assertFalse instant.isBefore(before)
+ assertFalse instant.isAfter(after)
+ }
+
+ @Test
+ void testNow() {
+ def before = System.currentTimeMillis()
+ def now = DefaultClock.INSTANCE.now()
+ def after = System.currentTimeMillis()
+ assertTrue now.getTime() >= before
+ assertTrue now.getTime() <= after
+ }
+}
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtBuilderTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtBuilderTest.groovy
index 93963e005..cd7ac03e3 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtBuilderTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtBuilderTest.groovy
@@ -34,6 +34,7 @@ import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.Provider
import java.security.SecureRandom
+import java.time.Instant
import static org.easymock.EasyMock.*
import static org.junit.Assert.*
@@ -449,6 +450,35 @@ class DefaultJwtBuilderTest {
assertTrue builder.claimsBuilder.isEmpty()
}
+ @Test
+ void testInstantClaims() {
+ def iat = Instant.parse('2026-10-03T10:00:00.123Z')
+ builder.issuedAt(iat).notBefore(iat.plusSeconds(1)).expiration(iat.plusSeconds(2))
+ Claims claims = builder.claimsBuilder.build()
+ assertEquals Instant.parse('2026-10-03T10:00:00Z'), claims.issuedAt()
+ assertEquals Instant.parse('2026-10-03T10:00:01Z'), claims.notBefore()
+ assertEquals Instant.parse('2026-10-03T10:00:02Z'), claims.expiration()
+ }
+
+ @Test
+ void testDateClaimsDelegateToInstant() {
+ def date = new Date(1700000000123L)
+ builder.issuedAt(date).notBefore(date).expiration(date)
+ Claims claims = builder.claimsBuilder.build()
+ def expected = Instant.ofEpochSecond(1700000000L)
+ assertEquals expected, claims.issuedAt()
+ assertEquals expected, claims.notBefore()
+ assertEquals expected, claims.expiration()
+ }
+
+ @Test
+ void testNullInstantClaimsRemoveValues() {
+ def now = Instant.now()
+ builder.issuedAt(now).notBefore(now).expiration(now)
+ builder.issuedAt((Instant) null).notBefore((Instant) null).expiration((Instant) null)
+ assertTrue builder.claimsBuilder.isEmpty()
+ }
+
@Test(expected = IllegalArgumentException)
void testBase64UrlEncodeWithNullArgument() {
new DefaultJwtBuilder().base64UrlEncodeWith(null)
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtParserTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtParserTest.groovy
index 4c41142c2..ca67afeb3 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtParserTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtParserTest.groovy
@@ -17,7 +17,6 @@ package io.jsonwebtoken.impl
import com.fasterxml.jackson.databind.ObjectMapper
import io.jsonwebtoken.*
-import io.jsonwebtoken.impl.lang.JwtDateConverter
import io.jsonwebtoken.impl.lang.Services
import io.jsonwebtoken.impl.security.TestKeys
import io.jsonwebtoken.io.AbstractDeserializer
@@ -32,6 +31,8 @@ import org.junit.Test
import javax.crypto.Mac
import javax.crypto.SecretKey
+import java.time.Instant
+import java.time.temporal.ChronoUnit
import static org.junit.Assert.*
@@ -262,8 +263,8 @@ class DefaultJwtParserTest {
void testExpiredExceptionMessage() {
long differenceMillis = 843 // arbitrary, anything > 0 is fine
- def exp = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def later = new Date(exp.getTime() + differenceMillis)
+ def exp = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def later = exp.plusMillis(differenceMillis)
def s = Jwts.builder().expiration(exp).compact()
try {
@@ -281,8 +282,8 @@ class DefaultJwtParserTest {
void testNotBeforeExceptionMessage() {
long differenceMillis = 3842 // arbitrary, anything > 0 is fine
- def nbf = JwtDateConverter.INSTANCE.applyFrom(System.currentTimeMillis() / 1000L)
- def earlier = new Date(nbf.getTime() - differenceMillis)
+ def nbf = Instant.now().truncatedTo(ChronoUnit.SECONDS)
+ def earlier = nbf.minusMillis(differenceMillis)
def s = Jwts.builder().notBefore(nbf).compact()
try {
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/FixedClockTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/FixedClockTest.groovy
index 3e39f03fd..40037b761 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/impl/FixedClockTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/FixedClockTest.groovy
@@ -16,6 +16,9 @@
package io.jsonwebtoken.impl
import org.junit.Test
+
+import java.time.Instant
+
import static org.junit.Assert.*
class FixedClockTest {
@@ -29,6 +32,48 @@ class FixedClockTest {
Thread.sleep(100)
def date2 = clock.now()
- assertSame date1, date2
+ assertEquals date1, date2
+ assertNotSame date1, date2 // a new copy is returned on each call; the seed is not mutable externally
+ }
+
+ @Test
+ void testFixedClockDefaultConstructorInstant() {
+ def clock = new FixedClock()
+
+ def instant1 = clock.instant()
+ Thread.sleep(100)
+ def instant2 = clock.instant()
+
+ assertSame instant1, instant2
+ }
+
+ @Test
+ void testInstantConstructor() {
+ def instant = Instant.parse('2026-10-03T10:15:30.123Z')
+ def clock = new FixedClock(instant)
+ assertSame instant, clock.instant()
+ assertEquals Date.from(instant), clock.now()
+ }
+
+ @Test
+ void testDateConstructor() {
+ def date = new Date(1700000000123L)
+ def clock = new FixedClock(date)
+ assertEquals date.toInstant(), clock.instant()
+ assertEquals date, clock.now()
+ }
+
+ @Test
+ void testNullDateConstructor() {
+ def clock = new FixedClock((Date) null)
+ assertNull clock.instant()
+ assertNull clock.now()
+ }
+
+ @Test
+ void testMillisConstructor() {
+ def clock = new FixedClock(1700000000123L)
+ assertEquals Instant.ofEpochMilli(1700000000123L), clock.instant()
+ assertEquals new Date(1700000000123L), clock.now()
}
}
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtDateConverterTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtDateConverterTest.groovy
index bd25bdcb3..6f418da05 100644
--- a/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtDateConverterTest.groovy
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtDateConverterTest.groovy
@@ -17,22 +17,58 @@ package io.jsonwebtoken.impl.lang
import org.junit.Test
-import static org.junit.Assert.assertNull
+import java.time.Instant
+
+import static org.junit.Assert.*
class JwtDateConverterTest {
@Test
- void testApplyToNull() {
- assertNull JwtDateConverter.INSTANCE.applyTo(null)
+ void testToDateWithNull() {
+ assertNull JwtDateConverter.toDate(null)
}
@Test
- void testApplyFromNull() {
- assertNull JwtDateConverter.INSTANCE.applyFrom(null)
+ void testToDateWithDate() {
+ def date = new Date()
+ assertSame date, JwtDateConverter.toDate(date)
}
@Test
- void testToDateWithNull() {
- assertNull JwtDateConverter.toDate(null)
+ void testToDateWithCalendar() {
+ def cal = Calendar.getInstance()
+ assertEquals cal.getTime(), JwtDateConverter.toDate(cal)
+ }
+
+ @Test
+ void testToDateNumberIsMillis() {
+ assertEquals new Date(1700000000123L), JwtDateConverter.toDate(1700000000123L)
+ }
+
+ @Test
+ void testToDateWithIso8601String() {
+ assertEquals Date.from(Instant.parse('2023-11-14T22:13:20.123Z')),
+ JwtDateConverter.toDate('2023-11-14T22:13:20.123Z')
+ }
+
+ @Test
+ void testToDateWithInvalidString() {
+ try {
+ JwtDateConverter.toDate('not a date')
+ fail()
+ } catch (IllegalArgumentException expected) {
+ assertTrue expected.getMessage().startsWith(
+ 'String value is not a JWT NumericDate, nor is it ISO-8601-formatted. All heuristics exhausted.')
+ }
+ }
+
+ @Test
+ void testToDateWithUnsupportedType() {
+ try {
+ JwtDateConverter.toDate(new Object())
+ fail()
+ } catch (IllegalArgumentException expected) {
+ assertEquals 'Cannot create Date from object of type java.lang.Object.', expected.getMessage()
+ }
}
}
diff --git a/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtInstantConverterTest.groovy b/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtInstantConverterTest.groovy
new file mode 100644
index 000000000..330d058a7
--- /dev/null
+++ b/impl/src/test/groovy/io/jsonwebtoken/impl/lang/JwtInstantConverterTest.groovy
@@ -0,0 +1,127 @@
+/*
+ * Copyright © 2026 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.impl.lang
+
+import org.junit.Test
+
+import java.time.DateTimeException
+import java.time.Instant
+
+import static org.junit.Assert.*
+
+class JwtInstantConverterTest {
+
+ @Test
+ void testApplyToNull() {
+ assertNull JwtInstantConverter.INSTANCE.applyTo(null)
+ }
+
+ @Test
+ void testApplyToReturnsSeconds() {
+ def instant = Instant.ofEpochSecond(1700000000L, 999_999_999)
+ assertEquals 1700000000L, JwtInstantConverter.INSTANCE.applyTo(instant)
+ }
+
+ @Test
+ void testApplyFromNull() {
+ assertNull JwtInstantConverter.INSTANCE.applyFrom(null)
+ }
+
+ @Test
+ void testApplyFromNumberIsSeconds() {
+ assertEquals Instant.ofEpochSecond(1700000000L), JwtInstantConverter.INSTANCE.applyFrom(1700000000L)
+ assertEquals Instant.ofEpochSecond(1700000000L), JwtInstantConverter.INSTANCE.applyFrom(1700000000)
+ }
+
+ @Test
+ void testApplyFromNumericStringIsSeconds() {
+ assertEquals Instant.ofEpochSecond(1700000000L), JwtInstantConverter.INSTANCE.applyFrom('1700000000')
+ }
+
+ @Test
+ void testApplyFromIso8601String() {
+ assertEquals Instant.parse('2023-11-14T22:13:20Z'),
+ JwtInstantConverter.INSTANCE.applyFrom('2023-11-14T22:13:20Z')
+ assertEquals Instant.parse('2023-11-14T22:13:20.123Z'),
+ JwtInstantConverter.INSTANCE.applyFrom('2023-11-14T22:13:20.123Z')
+ }
+
+ @Test
+ void testApplyFromInvalidString() {
+ try {
+ JwtInstantConverter.INSTANCE.applyFrom('not a date')
+ fail()
+ } catch (IllegalArgumentException expected) {
+ assertTrue expected.getMessage().startsWith(
+ 'String value is not a JWT NumericDate, nor is it ISO-8601-formatted. All heuristics exhausted.')
+ }
+ }
+
+ @Test
+ void testApplyFromSecondsOutOfRange() {
+ try {
+ JwtInstantConverter.INSTANCE.applyFrom(Long.MAX_VALUE)
+ fail()
+ } catch (IllegalArgumentException expected) {
+ assertTrue expected.getMessage().startsWith("Value '${Long.MAX_VALUE}' is outside the supported Instant range.")
+ assertTrue expected.getCause() instanceof DateTimeException
+ }
+ }
+
+ @Test
+ void testToInstantWithNull() {
+ assertNull JwtInstantConverter.toInstant(null)
+ }
+
+ @Test
+ void testToInstantWithInstant() {
+ def instant = Instant.now()
+ assertSame instant, JwtInstantConverter.toInstant(instant)
+ }
+
+ @Test
+ void testToInstantWithDate() {
+ def date = new Date()
+ assertEquals date.toInstant(), JwtInstantConverter.toInstant(date)
+ }
+
+ @Test
+ void testToInstantWithCalendar() {
+ def cal = Calendar.getInstance()
+ assertEquals cal.toInstant(), JwtInstantConverter.toInstant(cal)
+ }
+
+ @Test
+ void testToInstantNumberIsMillis() {
+ assertEquals Instant.ofEpochMilli(1700000000123L), JwtInstantConverter.toInstant(1700000000123L)
+ }
+
+ @Test
+ void testToInstantWithUnsupportedType() {
+ try {
+ JwtInstantConverter.toInstant(new Object())
+ fail()
+ } catch (IllegalArgumentException expected) {
+ assertEquals 'Cannot create Instant from object of type java.lang.Object.', expected.getMessage()
+ }
+ }
+
+ @Test
+ void testToSpecInstantWithInstant() {
+ def instant = Instant.now()
+ assertSame instant, JwtInstantConverter.toSpecInstant(instant)
+ }
+}
diff --git a/pom.xml b/pom.xml
index 3cf2c82b2..dc69d93d5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -94,7 +94,10 @@
${basedir}
- 0.11.2
+
+ 0.13.0
3.4.2
3.14.0
@@ -443,6 +446,14 @@
true
+
+
+ io\.jsonwebtoken\.lang\.Supplier
+
+