Expiry, clock skew and signing keys from configuration
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A stolen token keeps working until its expiry, and the server cannot take it back. So the damage depends on two settings: how long a token lives and how strong the signing key is.
Short access-token lifetimes and the exp check
exp / nbf are two JWT claims: the expiry time and the not-before time, in seconds since 1970 UTC. A token used after exp or before nbf is rejected by the JwtTimestampValidator.
A token copied from a shared college computer or a log file works until exp. The commands below cut the lifetime to 20 seconds, only to watch a token expire.
Example 1 · Watching a token expire
Runs in: the shoplite-api Spring Boot project
# Lifetime cut to 20 seconds and no clock allowance, only to watch expiry happenjava -jar target/shoplite-api-1.0.0.jar --shoplite.jwt.access-token-ttl=20s --shoplite.jwt.clock-skew=0sTOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \ -d '{"email":"asha.rao@example.com","password":"asha-dev-password"}' | jq -r .accessToken)date -u +%T; curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"sleep 22date -u +%T; curl -i http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"08:01:02
200
08:01:25
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Jwt expired at 2026-10-16T08:01:22Z", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The access token is invalid or has expired. Sign in again.","instance":"/api/v1/me"}What this code does
- The same token answers 200 at 08:01:02 and 401 at 08:01:25:
expwas 08:01:22 UTC. - The
WWW-Authenticateheader carries the exact reason for the client developer; the body keeps the one safe sentence. - Command-line
--shoplite.jwt...arguments overrideapplication.properties, which makes such experiments easy without editing files.
The error is "Jwt expired at ...", and ShopLite answers 401 with "The access token is invalid or has expired." With 15 minutes, a copied token is soon useless, while a 30-day token is as good as the password for 30 days.
Short tokens would make users sign in often, which nobody accepts on a phone. The Refresh tokens lesson fixes that: a long-lived refresh token, stored and revocable on the server, gets new 15-minute access tokens without asking for the password again.
Clock skew: JwtTimestampValidator(Duration)
Clock skew is the small difference between the clocks of two computers. A validator allows that much difference on exp and nbf, so a good token is not rejected because the checking server runs ahead.
If the server that made a token is 10 seconds ahead of the one checking it, a good token could fail early. new JwtTimestampValidator(Duration.ofSeconds(30)) allows a small window.
Example 2 · A 30-second clock allowance
Runs in: the shoplite-api Spring Boot project
# Same 20-second tokens, now with the normal 30-second clock allowancejava -jar target/shoplite-api-1.0.0.jar --shoplite.jwt.access-token-ttl=20s --shoplite.jwt.clock-skew=30sdate -u +%T # right after loginsleep 25; date -u +%T; curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"sleep 30; date -u +%T; curl -i http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"08:04:37 08:05:03 200 08:05:35 HTTP/1.1 401 WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Jwt expired at 2026-10-16T08:04:56Z", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
What this code does
- The token's
expwas 08:04:56. At 08:05:03, 7 seconds later, it is still accepted because of the 30-second allowance. - At 08:05:35, 39 seconds after
exp, it is rejected: the allowance is a small window, not a longer lifetime. - With
clock-skew=0s(Example 1) the same token would have failed at 08:04:56.
The default allowance is 60 seconds. ShopLite sets 30 seconds in shoplite.jwt.clock-skew: servers synchronise their clocks (NTP), so a small allowance is enough, and every second of allowance is a second longer that a stolen token works. Example 2 shows a 20-second token still accepted 7 seconds after exp and rejected 39 seconds after.
Predict the output
Accepted or expired?
Read the code and pick what it prints.
Round 1 of 3
The allowance is 30 seconds. What does the request get?
0s) is fine on one machine, but between servers it causes random 401s that are hard to reproduce.Validating the issuer and adding custom validators
JwtIssuerValidator is a token validator that rejects a JWT whose iss claim is not the expected issuer, here ShopLite's own shoplite-api.
Keys get reused: a test server, a second app or a future login service may sign with a key that the API also knows. The issuer check says "this token was made for us".
// A custom rule next to ShopLite's two validators: every token must carry at least one roleOAuth2TokenValidator<Jwt> hasRoles = new JwtClaimValidator<List<String>>("roles", roles -> roles != null && !roles.isEmpty());decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>( new JwtTimestampValidator(properties.clockSkew()), new JwtIssuerValidator(properties.issuer()), hasRoles));Example 3 · A token from another issuer
Runs in: the shoplite-api Spring Boot project
# Restart with another issuer, then send a token that the normal server made a few minutes agojava -jar target/shoplite-api-1.0.0.jar --shoplite.jwt.issuer=shoplite-api-v2curl -i http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: The iss claim is not valid", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The access token is invalid or has expired. Sign in again.","instance":"/api/v1/me"}What this code does
- The signature is fine (same key) and the token has not expired, yet it fails: "The iss claim is not valid".
- That is
JwtIssuerValidator(properties.issuer())fromJwtConfigat work. - In real life this protects the API from tokens that another service signed with a reused key.
With one shared HMAC key the signature already proves who made the token, so the issuer check is a second line of defence. Validators are combined with DelegatingOAuth2TokenValidator, and you can add your own with JwtClaimValidator, for example "the token must have a non-empty roles claim".
Calling setJwtValidator replaces the defaults, so the list must include the timestamp validator again, as ShopLite's JwtConfig does.
A @ConfigurationProperties record with the secret from the environment
The signing secret must never sit in Git. A record bound to the shoplite.jwt.* settings reads it from the environment and checks it.
Example 4 · src/main/java/com/shoplite/auth/JwtProperties.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.auth;
import java.time.Duration;import java.util.Base64;
import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.bind.DefaultValue;
/** * Token settings under "shoplite.jwt". The secret comes from the JWT_SECRET environment variable: * a Base64 text of at least 32 random bytes (openssl rand -base64 32). */@ConfigurationProperties("shoplite.jwt")public record JwtProperties( String secret, @DefaultValue("shoplite-api") String issuer, @DefaultValue("15m") Duration accessTokenTtl, @DefaultValue("7d") Duration refreshTokenTtl, @DefaultValue("30s") Duration clockSkew) {
/** HS256 needs a key of at least 256 bits (32 bytes). */ static final int MIN_KEY_BYTES = 32;
/** Runs while Spring binds the properties, so a missing or weak key stops the app at startup. */ public JwtProperties { if (secret == null || secret.isBlank()) { throw new IllegalArgumentException("shoplite.jwt.secret is empty. Set the JWT_SECRET environment variable."); } byte[] key; try { key = Base64.getDecoder().decode(secret.trim()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("shoplite.jwt.secret must be Base64 text (openssl rand -base64 32)."); } if (key.length < MIN_KEY_BYTES) { throw new IllegalArgumentException("shoplite.jwt.secret is " + key.length + " bytes; HS256 needs at least " + MIN_KEY_BYTES + " random bytes."); } }
/** The HMAC-SHA256 key that signs and checks every access token. */ public SecretKey signingKey() { return new SecretKeySpec(Base64.getDecoder().decode(secret.trim()), "HmacSHA256"); }
/** Records print every field; this one must never print the secret. */ @Override public String toString() { return "JwtProperties[secret=***, issuer=" + issuer + ", accessTokenTtl=" + accessTokenTtl + ", refreshTokenTtl=" + refreshTokenTtl + ", clockSkew=" + clockSkew + "]"; }}
/*# src/main/resources/application.properties# Access tokens (JWT, HS256). The secret comes from the JWT_SECRET environment variable, never from this file.shoplite.jwt.secret=${JWT_SECRET:}shoplite.jwt.issuer=shoplite-apishoplite.jwt.access-token-ttl=15mshoplite.jwt.refresh-token-ttl=7dshoplite.jwt.clock-skew=30s
# src/test/resources/application-test.properties# A key for tests only: it signs nothing outside the test run (32 bytes, Base64)shoplite.jwt.secret=dGVzdC1vbmx5LWtleS1uZXZlci11c2VkLWluLXByb2Q=*/$ mvn test ... [INFO] Running com.shoplite.auth.JwtPropertiesTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 s -- in com.shoplite.auth.JwtPropertiesTest
What this code does
- The compact constructor runs during binding, so
JwtPropertiesTestcan check the three key rules with plainnew JwtProperties(...)calls, no Spring needed. signingKey()decodes the Base64 text into an HMAC-SHA256SecretKey, used by both the encoder and the decoder.toString()printssecret=***, never the key.
JwtProperties holds secret, issuer, accessTokenTtl, refreshTokenTtl and clockSkew, with defaults through @DefaultValue. Durations bind from text such as 15m, 7d and 30s. Both JwtConfig and TokenService receive the record, so no class reads properties by name.
The secret line is shoplite.jwt.secret=${JWT_SECRET:}: the value comes from the JWT_SECRET environment variable, never from a file in Git. The empty default after the colon makes a missing variable reach the record as an empty string, where the record can stop with a clear message. Tests get their own test-only key in application-test.properties. The record also overrides toString(), because a log line showing the secret would be a leak.
Key length, failing at startup, and rotating keys
Key rotation is switching to a new signing key, on a schedule or at once after a leak. Access tokens signed with the old key stop passing the check.
A short secret can be guessed offline. The program below measures key lengths, and the commands after it show a bad key stopping the app at startup.
Example 5 · Key length in numbers
import java.nio.charset.StandardCharsets;import java.security.SecureRandom;import java.util.Base64;
/** Why "shoplite-secret" is not a key, and what a real HS256 key looks like. */public class KeyLengthDemo {
static void describe(String label, String base64Secret) { byte[] key = Base64.getDecoder().decode(base64Secret); String verdict = key.length >= 32 ? "ok for HS256" : "too short for HS256"; System.out.println(label + ": " + base64Secret.length() + " Base64 characters = " + key.length + " bytes = " + key.length * 8 + " bits -> " + verdict); }
public static void main(String[] args) { String weak = Base64.getEncoder().encodeToString("shoplite-secret".getBytes(StandardCharsets.UTF_8)); describe("A password-like secret", weak);
byte[] random = new byte[32]; new SecureRandom().nextBytes(random); // what openssl rand -base64 32 does describe("32 random bytes ", Base64.getEncoder().encodeToString(random)); }}A password-like secret: 20 Base64 characters = 15 bytes = 120 bits -> too short for HS256 32 random bytes : 44 Base64 characters = 32 bytes = 256 bits -> ok for HS256
What this code does
- Base64 turns every 3 bytes into 4 characters, so a 32-byte key is 44 characters ending in
=. shoplite-secretis only 15 bytes, and they are ordinary words, which makes guessing even easier than the length suggests.SecureRandomis Java's random generator for keys;java.util.Randomis predictable and must never make secrets.
Example 6 · The app refuses to start with a bad key
Runs in: the shoplite-api Spring Boot project
# 1. a password-like secret (15 bytes)export JWT_SECRET=$(echo -n "shoplite-secret" | base64) # c2hvcGxpdGUtc2VjcmV0java -jar target/shoplite-api-1.0.0.jar# 2. text that is not Base64export JWT_SECRET="my-shoplite-secret!"java -jar target/shoplite-api-1.0.0.jar# the right way: 32 random bytesexport JWT_SECRET=$(openssl rand -base64 32)***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'shoplite.jwt' to com.shoplite.auth.JwtProperties:
Reason: java.lang.IllegalArgumentException: shoplite.jwt.secret is 15 bytes; HS256 needs at least 32 random bytes.
Action:
Update your application's configuration
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'shoplite.jwt' to com.shoplite.auth.JwtProperties:
Reason: java.lang.IllegalArgumentException: shoplite.jwt.secret must be Base64 text (openssl rand -base64 32).
Action:
Update your application's configurationWhat this code does
- Both failures happen at startup, before the server takes a single request, with a message that says exactly what to fix.
- Spring Boot's failure analyser shows the record's own
IllegalArgumentExceptiontext under "Reason". - A missing
JWT_SECRETstops the app the same way: "shoplite.jwt.secret is empty. Set the JWT_SECRET environment variable."
HS256 needs a key of at least 256 bits (32 bytes), as long as its SHA-256 output (RFC 7518). With a short secret such as shoplite-secret, an attacker takes any token, tries millions of guesses per second until one gives the same signature, and then signs ADMIN tokens. So ShopLite's secret is 32 random bytes in Base64, made with openssl rand -base64 32. The record's compact constructor checks the secret while Spring binds it: missing, not Base64, or shorter than 32 bytes, and the app refuses to start, which is far better than running with a weak key for months.
In ShopLite, a new JWT_SECRET makes every access token fail within 15 minutes at most; clients use their refresh token (stored in the database, not signed with this key) to get new ones. Bigger systems keep the old key for checking only until its last token expires, and pick the key by the header's kid.
Next step
Check your understanding
11 quick questions