JWT
suggest changeA JSON Web Token (JWT, RFC 7519) is a compact, URL-safe string that carries a set of claims (facts such as "the user is alice, valid until 10:15") plus a signature. Whoever has the right key can check that the claims were issued by a trusted party and were not modified. JWTs are used as OAuth 2.0 access tokens, OpenID Connect ID tokens, session tokens for stateless APIs, and signed links.
The JDK has everything needed to create and verify a JWT by hand (Base64, Mac, Signature), but no JSON parser and no claim validation. In production code, use a library: JJWT, Auth0 java-jwt or Nimbus JOSE+JWT. This article shows both approaches, so you know what the library does for you.
Anatomy of a JWT
A signed JWT (technically a JWS) has three parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIsIm5hbWUiOiJBbGljZSIsImFkbWluIjp0cnVlLCJpYXQiOjE3NjAwMDAwMDAsImV4cCI6MTc2MDAwMzYwMH0.w6BnPatGQzfkRQkQBMBE5kXdFV1R5PUU7TUqPR91gQw
- header: JSON saying how the token is signed, e.g.
{"alg":"HS256","typ":"JWT"} - payload: JSON object with the claims
- signature: computed over the ASCII string
base64url(header) + "." + base64url(payload)
Each part is base64url encoded without = padding (- and _ instead of + and /). Encoding is not encryption: anyone holding the token can read the payload. The signature only guarantees integrity and authenticity. Never put passwords or other secrets in a JWT payload.
Registered claim names, all optional:
| Claim | Meaning |
|---|---|
iss |
issuer, who created the token (often a URL) |
sub |
subject, usually a user id |
aud |
audience, which service(s) the token is meant for (string or array) |
exp |
expiration time, seconds since the Unix epoch |
nbf |
not before, token is invalid before this time |
iat |
issued at |
jti |
unique token id, useful for revocation lists and replay detection |
Times are seconds, not milliseconds. Use Instant.getEpochSecond(), not System.currentTimeMillis().
Common signing algorithms (the alg header):
alg |
Kind | JDK algorithm |
|---|---|---|
HS256, HS384, HS512 |
HMAC with a shared secret | HmacSHA256, ... |
RS256, RS384, RS512 |
RSA PKCS#1 v1.5 | SHA256withRSA, ... |
PS256, PS384, PS512 |
RSA-PSS | RSASSA-PSS + PSSParameterSpec |
ES256, ES384, ES512 |
ECDSA (P-256, P-384, P-521) | SHA256withECDSAinP1363Format, ... |
EdDSA |
Ed25519 | Ed25519 (Java 15+) |
With HMAC, the same secret signs and verifies, so every verifier can also mint tokens. With RSA, ECDSA and EdDSA, the issuer keeps the private key and verifiers only need the public key. Use asymmetric keys when tokens are verified by services other than the one that issued them.
Decoding a JWT with the JDK
Reading the claims needs only Base64.getUrlDecoder(), which accepts input without padding:
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DecodeJwt {
public static void main(String[] args) {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
+ ".eyJzdWIiOiJhbGljZSIsIm5hbWUiOiJBbGljZSIsImFkbWluIjp0cnVlLCJpYXQiOjE3NjAwMDAwMDAsImV4cCI6MTc2MDAwMzYwMH0"
+ ".w6BnPatGQzfkRQkQBMBE5kXdFV1R5PUU7TUqPR91gQw";
String[] parts = token.split("\\.");
Base64.Decoder dec = Base64.getUrlDecoder();
String header = new String(dec.decode(parts[0]), StandardCharsets.UTF_8);
String payload = new String(dec.decode(parts[1]), StandardCharsets.UTF_8);
System.out.println(header);
System.out.println(payload);
}
}
{"alg":"HS256","typ":"JWT"}
{"sub":"alice","name":"Alice","admin":true,"iat":1760000000,"exp":1760003600}
Decoding is fine for debugging, or for a client that wants to show the user name or check exp before refreshing a token. A server must never make access decisions based on a token it only decoded: anyone can produce a token with "admin":true.
Creating and verifying HS256 by hand
HS256 is HMAC-SHA256 over the signing input. The code below produces exactly the token shown above:
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Hs256 {
static final Base64.Encoder ENC = Base64.getUrlEncoder().withoutPadding();
static final Base64.Decoder DEC = Base64.getUrlDecoder();
static byte[] hmacSha256(byte[] key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.US_ASCII));
}
static String sign(String headerJson, String payloadJson, byte[] key) throws Exception {
String signingInput = ENC.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8))
+ "." + ENC.encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
return signingInput + "." + ENC.encodeToString(hmacSha256(key, signingInput));
}
/** Returns the payload JSON if the signature is valid, otherwise throws. */
static String verify(String token, byte[] key) throws Exception {
String[] parts = token.split("\\.");
if (parts.length != 3) throw new SecurityException("not a JWS");
String header = new String(DEC.decode(parts[0]), StandardCharsets.UTF_8);
// Pin the algorithm: never let the token choose how it is verified.
if (!header.replace(" ", "").contains("\"alg\":\"HS256\"")) {
throw new SecurityException("unexpected alg: " + header);
}
byte[] expected = hmacSha256(key, parts[0] + "." + parts[1]);
byte[] actual = DEC.decode(parts[2]);
// Constant-time comparison; Arrays.equals leaks timing information.
if (!MessageDigest.isEqual(expected, actual)) {
throw new SecurityException("bad signature");
}
return new String(DEC.decode(parts[1]), StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
byte[] key = "a-string-secret-at-least-256-bits-long".getBytes(StandardCharsets.UTF_8);
String header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
String payload = "{\"sub\":\"alice\",\"name\":\"Alice\",\"admin\":true,"
+ "\"iat\":1760000000,\"exp\":1760003600}";
String token = sign(header, payload, key);
System.out.println(token);
System.out.println(verify(token, key));
// Tamper with the payload: replace it with a different one, keep the signature.
String[] p = token.split("\\.");
String forged = p[0] + "." + ENC.encodeToString(
"{\"sub\":\"mallory\",\"admin\":true}".getBytes(StandardCharsets.UTF_8)) + "." + p[2];
try {
verify(forged, key);
} catch (SecurityException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIsIm5hbWUiOiJBbGljZSIsImFkbWluIjp0cnVlLCJpYXQiOjE3NjAwMDAwMDAsImV4cCI6MTc2MDAwMzYwMH0.w6BnPatGQzfkRQkQBMBE5kXdFV1R5PUU7TUqPR91gQw
{"sub":"alice","name":"Alice","admin":true,"iat":1760000000,"exp":1760003600}
rejected: bad signature
A valid signature is only half the job. After verifying, you still have to parse the payload with a JSON library (see JSON in Java) and check exp, nbf, iss and aud. The string check of the header above is also simplistic. These are the reasons to use a library.
An HMAC key must be at least as long as the hash output: 32 random bytes for HS256. Generate one with SecureRandom and store it base64-encoded (see Generate Cryptographically Random Data), rather than using a human-made password:
byte[] secret = new byte[32];
new java.security.SecureRandom().nextBytes(secret);
System.out.println(Base64.getEncoder().encodeToString(secret));
RS256 and ES256 with java.security.Signature
The asymmetric algorithms use java.security.Signature with a key pair (see Compute and Verify Digital Signatures). The signature bytes are base64url-encoded just like the HMAC:
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.util.Base64;
public class AsymmetricJwt {
static final Base64.Encoder ENC = Base64.getUrlEncoder().withoutPadding();
static String sign(String alg, String jdkAlg, PrivateKey key, String payload) throws Exception {
String header = "{\"alg\":\"" + alg + "\",\"typ\":\"JWT\"}";
String input = ENC.encodeToString(header.getBytes(StandardCharsets.UTF_8))
+ "." + ENC.encodeToString(payload.getBytes(StandardCharsets.UTF_8));
Signature s = Signature.getInstance(jdkAlg);
s.initSign(key);
s.update(input.getBytes(StandardCharsets.US_ASCII));
return input + "." + ENC.encodeToString(s.sign());
}
static boolean verify(String token, String jdkAlg, PublicKey key) throws Exception {
int dot = token.lastIndexOf('.');
Signature s = Signature.getInstance(jdkAlg);
s.initVerify(key);
s.update(token.substring(0, dot).getBytes(StandardCharsets.US_ASCII));
return s.verify(Base64.getUrlDecoder().decode(token.substring(dot + 1)));
}
public static void main(String[] args) throws Exception {
String payload = "{\"sub\":\"alice\",\"exp\":1760003600}";
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048);
KeyPair rsa = rsaGen.generateKeyPair();
String rs = sign("RS256", "SHA256withRSA", rsa.getPrivate(), payload);
System.out.println("RS256 valid: " + verify(rs, "SHA256withRSA", rsa.getPublic()));
KeyPairGenerator ecGen = KeyPairGenerator.getInstance("EC");
ecGen.initialize(new ECGenParameterSpec("secp256r1"));
KeyPair ec = ecGen.generateKeyPair();
String es = sign("ES256", "SHA256withECDSAinP1363Format", ec.getPrivate(), payload);
System.out.println("ES256 valid: " + verify(es, "SHA256withECDSAinP1363Format", ec.getPublic()));
System.out.println("ES256 signature length: "
+ Base64.getUrlDecoder().decode(es.substring(es.lastIndexOf('.') + 1)).length);
}
}
RS256 valid: true
ES256 valid: true
ES256 signature length: 64
Note SHA256withECDSAinP1363Format (Java 9+). Plain SHA256withECDSA produces a DER-encoded signature of varying length (about 70-72 bytes), but JWS requires the fixed 64-byte R || S form. Using the wrong one is a classic source of "signature invalid" errors when talking to other platforms.
JJWT
JJWT has a fluent API and validates exp and nbf automatically. It is split into an API jar and runtime implementation jars:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.13.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson -->
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
Creating and parsing a token:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.crypto.SecretKey;
public class JjwtExample {
public static void main(String[] args) {
// In real code load the secret from configuration or a secret manager.
SecretKey key = Keys.hmacShaKeyFor(
Decoders.BASE64.decode("q8x0dYb2q0Jm3YQ2c6yH2m4m9sXyR0n3Jt5kV7wZp1E="));
Instant now = Instant.now();
String jws = Jwts.builder()
.issuer("https://auth.example.com")
.subject("alice")
.audience().add("orders-api").and()
.claim("roles", List.of("user", "admin"))
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(15, ChronoUnit.MINUTES)))
.id(UUID.randomUUID().toString())
.signWith(key) // HS256 chosen from the key size
.compact();
System.out.println(jws);
Claims claims = Jwts.parser()
.verifyWith(key)
.requireIssuer("https://auth.example.com")
.requireAudience("orders-api")
.clockSkewSeconds(30)
.build()
.parseSignedClaims(jws)
.getPayload();
System.out.println(claims.getSubject());
System.out.println(claims.get("roles", List.class));
System.out.println(claims.getExpiration().toInstant());
}
}
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJhbGljZSIs...
alice
[user, admin]
2026-10-17T10:15:42Z
Points worth knowing:
Keys.hmacShaKeyForthrowsWeakKeyExceptionif the key is shorter than 256 bits.Jwts.SIG.HS256.key().build()generates a fresh random key, andJwts.SIG.RS256.keyPair().build()orJwts.SIG.ES256.keyPair().build()a key pair.parseSignedClaimsaccepts only signed tokens. Unsecured tokens ("alg":"none") are rejected unless you explicitly call.unsecured()on the parser builder, which you should not do.- For asymmetric keys, sign with the private key and verify with the public one:
.signWith(keyPair.getPrivate())and.verifyWith(keyPair.getPublic()). To pick the algorithm explicitly, use.signWith(key, Jwts.SIG.RS256). - Make the parser once and reuse it.
JwtParseris immutable and thread-safe.
Every failure is a subclass of io.jsonwebtoken.JwtException, so you can catch them separately or all together:
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
static Claims authenticate(JwtParser parser, String token) {
try {
return parser.parseSignedClaims(token).getPayload();
} catch (ExpiredJwtException e) {
// e.getClaims() is still available, e.g. to log who it was
throw new AuthException("token expired for " + e.getClaims().getSubject());
} catch (SignatureException e) {
throw new AuthException("bad signature");
} catch (IncorrectClaimException | MissingClaimException e) {
throw new AuthException("wrong issuer or audience: " + e.getClaimName());
} catch (JwtException | IllegalArgumentException e) {
// MalformedJwtException, UnsupportedJwtException, null/empty token...
throw new AuthException("invalid token");
}
}
AuthException is your own exception type. Do not send the exception message back to the client; a generic 401 Unauthorized is enough.
Auth0 java-jwt
java-jwt is a single dependency (it uses Jackson internally) with a similar fluent style:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.6.2</version>
</dependency>
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.time.Instant;
public class Auth0Example {
public static void main(String[] args) {
Algorithm alg = Algorithm.HMAC256("a-string-secret-at-least-256-bits-long");
Instant now = Instant.now();
String token = JWT.create()
.withIssuer("https://auth.example.com")
.withSubject("alice")
.withAudience("orders-api")
.withArrayClaim("roles", new String[] {"user", "admin"})
.withIssuedAt(now)
.withExpiresAt(now.plusSeconds(900))
.sign(alg);
// Build once, reuse: JWTVerifier is thread-safe.
JWTVerifier verifier = JWT.require(alg)
.withIssuer("https://auth.example.com")
.withAudience("orders-api")
.acceptLeeway(30)
.build();
try {
DecodedJWT jwt = verifier.verify(token);
System.out.println(jwt.getSubject());
System.out.println(jwt.getClaim("roles").asList(String.class));
System.out.println(jwt.getAlgorithm());
} catch (TokenExpiredException e) {
System.out.println("expired at " + e.getExpiredOn());
} catch (JWTVerificationException e) {
System.out.println("invalid: " + e.getMessage());
}
}
}
alice
[user, admin]
HS256
For RSA, pass typed keys: Algorithm.RSA256((RSAPublicKey) pub, (RSAPrivateKey) priv). A verifier only needs the public key, so use Algorithm.RSA256(pub, null). JWT.decode(token) returns a DecodedJWT without verifying anything; it is the library version of the JDK decoding shown earlier.
Verifying tokens from an identity provider (JWKS)
Tokens issued by Keycloak, Auth0, Okta, Entra ID, Google and other OpenID Connect providers are signed with rotating RSA or EC keys. The provider publishes the public keys as a JSON Web Key Set at a URL such as https://auth.example.com/.well-known/jwks.json, and the kid header of each token says which key signed it. Nimbus JOSE+JWT handles fetching, caching and key rotation:
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>10.10</version>
</dependency>
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.JWKSourceBuilder;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import java.net.URI;
import java.util.Set;
public class JwksVerifier {
private final DefaultJWTProcessor<SecurityContext> processor = new DefaultJWTProcessor<>();
public JwksVerifier(String issuer, String jwksUrl, String audience) throws Exception {
// Caches keys and refetches when a token has an unknown kid.
JWKSource<SecurityContext> keys = JWKSourceBuilder
.create(URI.create(jwksUrl).toURL())
.build();
// Only RS256 is accepted, whatever the token header claims.
processor.setJWSKeySelector(new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, keys));
processor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<>(
audience,
new JWTClaimsSet.Builder().issuer(issuer).build(),
Set.of("sub", "exp", "iat")));
}
public JWTClaimsSet verify(String token) throws Exception {
// Throws BadJOSEException (bad signature, expired, wrong iss/aud) or ParseException.
return processor.process(token, null);
}
}
In a Spring Boot application you usually don't write this code yourself: add spring-boot-starter-oauth2-resource-server and set spring.security.oauth2.resourceserver.jwt.issuer-uri. Spring discovers the JWKS URL from the provider's metadata and validates iss, exp and nbf for every request (Spring uses Nimbus internally). Obtaining tokens from such a provider is covered in OAuth.
Sending and receiving tokens over HTTP
A JWT access token is sent in the Authorization header with the Bearer scheme:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/orders"))
.header("Authorization", "Bearer " + token)
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
On the server, extract it carefully:
static String bearerToken(String authorizationHeader) {
if (authorizationHeader == null) return null;
String prefix = "Bearer ";
if (!authorizationHeader.regionMatches(true, 0, prefix, 0, prefix.length())) return null;
String token = authorizationHeader.substring(prefix.length()).trim();
return token.isEmpty() ? null : token;
}
Avoid putting tokens in URLs (query strings end up in server logs, browser history and Referer headers). In browser apps, an HttpOnly, Secure, SameSite cookie is safer than localStorage, which any injected script can read.
Security checklist
JWT bugs are usually verification bugs, not cryptography bugs:
- Pin the algorithm. Configure the verifier with the algorithm you expect. Never pick the verification algorithm from the token's
algheader. Otherwise an attacker can send"alg":"none"(no signature), or"alg":"HS256"signed with your RSA public key used as an HMAC secret (the "algorithm confusion" attack). All three libraries above protect against this when used as shown. - Always verify the signature before trusting any claim.
JWT.decodeand manual base64 decoding verify nothing. - Validate
exp,issandaud. Without an audience check, a token issued for another service of the same identity provider is accepted by yours. Allow only a small clock skew (30-60 seconds). - Keep access tokens short-lived (5-15 minutes) and use refresh tokens for long sessions. A signed JWT cannot be revoked before it expires unless you add a server-side check, for example a deny list of
jtivalues or a per-user "tokens issued before" timestamp. - Use strong keys: at least 256 random bits for HS256, at least 2048 bits for RSA. Keep them out of source control and rotate them; publish a
kidheader so old and new keys can coexist during rotation. - Payloads are readable. If the claims themselves must be confidential, use an encrypted JWT (JWE, supported by Nimbus and JJWT) or keep the data on the server and put only an opaque id in the token.
- Limit size and trust. Treat every claim as untrusted input until the signature is verified, and reject unusually large tokens early.
Choosing a library
| Library | Notes |
|---|---|
| JJWT | Clean builder API, JWS and JWE, JWK support, separate API/impl jars |
| Auth0 java-jwt | Small and simple, JWS only; use jwks-rsa from Auth0 for JWKS |
| Nimbus JOSE+JWT | Most complete (JWS, JWE, JWK, JWKS, OIDC), used by Spring Security; more verbose |
For a service that issues and verifies its own tokens, JJWT or java-jwt is the simplest choice. For validating tokens from an external identity provider, use Nimbus directly or let Spring Security do it.