gotchajavaspringMajor
JWT authentication: signing key must be consistent across restarts
Viewed 0 times
JWTsigning keysecrettoken invalidationrestartHMAC-SHA256
Error Messages
Problem
Using a randomly generated secret key for JWT signing that is created at application startup invalidates all existing tokens whenever the application restarts. Users are silently logged out after a deployment.
Solution
Store the JWT signing secret in configuration and inject it at startup:
For production, inject the secret via an environment variable or secrets manager.
# application.yml
app:
jwt:
secret: your-256-bit-secret-stored-in-env-or-vault
expiration-ms: 86400000@Component
public class JwtUtil {
@Value("${app.jwt.secret}")
private String secret;
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
}
public String generateToken(UserDetails user) {
return Jwts.builder()
.subject(user.getUsername())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + expirationMs))
.signWith(getSigningKey())
.compact();
}
}For production, inject the secret via an environment variable or secrets manager.
Why
JWTs are signed with a secret or private key. The verification step requires the same key used for signing. A new random key at each startup means previously issued tokens cannot be verified.
Gotchas
- The secret must be at least 256 bits (32 bytes) for HMAC-SHA256 — shorter keys throw a WeakKeyException
- Store secrets in environment variables or a vault, never in source control
- For multi-instance deployments, all instances must share the same signing key
Revisions (0)
No revisions yet.