Convert a JWT Payload to a Java POJO
Generate a Java POJO for the standard JWT claims (iss, sub, aud, exp, iat, nbf, jti) plus your application-specific claims.
Detailed Explanation
JWT Payloads in Java
A JSON Web Token's payload is a JSON object containing standard claims (defined by RFC 7519) and any custom claims your application adds.
Standard JWT Payload
{
"iss": "https://auth.example.com",
"sub": "user_42",
"aud": "api.example.com",
"exp": 1700000000,
"iat": 1699996400,
"nbf": 1699996400,
"jti": "a1b2c3d4",
"scope": "read:profile write:profile",
"roles": ["admin", "billing"]
}
Generated POJO
package com.example.security;
import java.util.List;
public class JwtPayload {
private String iss; // Issuer
private String sub; // Subject
private String aud; // Audience
private Long exp; // Expiration (Unix timestamp)
private Long iat; // Issued At
private Long nbf; // Not Before
private String jti; // JWT ID
private String scope;
private List<String> roles;
// accessors
}
Refinements
The auto-generated POJO is a good starting point. Three changes make it production-ready:
1. Convert timestamps to Instant
public Instant getExpiry() {
return Instant.ofEpochSecond(exp);
}
public boolean isExpired() {
return Instant.now().isAfter(getExpiry());
}
2. Handle aud as String OR List
The JWT spec allows aud to be either a single string or an array. Use a custom Jackson deserializer or model both with @JsonDeserialize(using = AudienceDeserializer.class).
3. Custom claims as a Map
Beyond the standard claims, your application may add arbitrary fields. Capture them with:
@JsonAnyGetter @JsonAnySetter
private Map<String, Object> customClaims = new HashMap<>();
@JsonAnyGetter and @JsonAnySetter make Jackson route unknown keys into the map automatically.
Working with Verified Tokens
Use a JWT library (java-jwt, nimbus-jose-jwt, jjwt) to verify the signature first, then map the verified payload claims into your POJO:
DecodedJWT jwt = JWT.require(Algorithm.RSA256(publicKey, null))
.build()
.verify(token);
ObjectMapper mapper = new ObjectMapper();
JwtPayload payload = mapper.readValue(jwt.getPayload(), JwtPayload.class);
Decoding for Inspection
If you only want to read claims for debugging (not for authentication), use the JWT Decoder tool to inspect the token contents in your browser before generating the POJO.
Use Case
Authentication middleware, custom claim extraction, and audit logging all benefit from a typed JWT payload class. Spring Security, Quarkus Security, and Micronaut Security can all be configured to deserialize JWT claims into a custom POJO.