Sub topic 3
Anatomy of a JWT
This chapter assumes you know what a bearer token is and that an HTTP request carries it in the Authorization header. The previous chapter covered that. Here you take a token apart. Later chapters cover which claims to trust and how Spring Security verifies the signature.
What a JWT is
A JSON Web Token (JWT) is a compact, URL-safe string that carries a set of claims, which are statements about a subject such as a user or a client. In practice, almost every JWT you meet as a resource server is a JSON Web Signature (JWS) in its compact form. The standards use three related names:
| Name | What it is | Typical use |
|---|---|---|
| JWT | The general token format and the claim rules | The umbrella term |
| JWS | A signed payload (integrity and authenticity) | Access tokens, which is what this tutorial handles |
| JWE | An encrypted payload (confidentiality) | Rare for access tokens |
When people say "JWT" for an access token, they usually mean a signed JWS. Spring Security's oauth2ResourceServer().jwt() support expects this form.
The three parts
A compact JWS has three segments separated by dots:
BASE64URL(header) . BASE64URL(payload) . BASE64URL(signature)Header
The header is a JSON object that describes how the token was produced. A typical header from an authorization server looks like this:
{
"alg": "RS256",
"typ": "JWT",
"kid": "2026-11-key-1"
}| Parameter | Meaning |
|---|---|
| `alg` | The signing algorithm, for example `RS256` or `ES256`. |
| `typ` | The media type of the token. Usually `JWT`. Some servers use `at+jwt` for access tokens. |
| `kid` | The key ID. It tells the verifier which key from a key set to use. |
The header is data supplied by whoever sends the token. A verifier must never let it decide what is trusted. The alg value is a request to use an algorithm, and your configuration decides whether that algorithm is acceptable.
Payload
The payload is also a JSON object. Its members are the claims:
{
"iss": "https://issuer.example.com/realms/demo",
"sub": "alice",
"aud": "orders-api",
"scope": "orders.read",
"exp": 1796117729,
"iat": 1796114129
}The meaning of each registered claim, and which ones to validate, is the next chapter's subject. For now, note that the payload may also hold any custom members the authorization server adds, such as roles or email.
Signature
The signature is the output of the signing algorithm over the ASCII bytes of BASE64URL(header) + "." + BASE64URL(payload). This string is the signing input. The signature does not cover the signature segment itself, and it does not cover a decoded form of the JSON. It covers the exact encoded text. Change one character in either of the first two segments and verification fails.
Base64url is encoding, not encryption
Each segment is encoded with Base64url, a variant of Base64 that replaces + with - and / with _ and drops the = padding. This makes the token safe to put in a header or URL.
The most common decoding mistake is using the standard Base64 decoder on a segment. It fails on - and _. In Java, use Base64.getUrlDecoder().
Building and reading a token by hand
The following program builds an HS256 token (HMAC with SHA-256) from scratch, then splits it and decodes the parts. HS256 uses a shared secret and needs no key pair, so the example is short. Production access tokens normally use an asymmetric algorithm such as RS256, but the structure is the same.
import static java.nio.charset.StandardCharsets.UTF_8;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class JwtAnatomy {
public static void main(String[] args) throws Exception {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
Base64.Decoder dec = Base64.getUrlDecoder();
String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
String payloadJson = "{\"sub\":\"alice\",\"iss\":\"https://issuer.example.com/realms/demo\"}";
String signingInput = enc.encodeToString(headerJson.getBytes(UTF_8))
+ "." + enc.encodeToString(payloadJson.getBytes(UTF_8));
byte[] secret = "demo-secret-demo-secret-demo-secret".getBytes(UTF_8);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
String signature = enc.encodeToString(mac.doFinal(signingInput.getBytes(UTF_8)));
String token = signingInput + "." + signature;
System.out.println("token: " + token);
String[] parts = token.split("\\.");
System.out.println("segments: " + parts.length);
System.out.println("header: " + new String(dec.decode(parts[0]), UTF_8));
System.out.println("payload: " + new String(dec.decode(parts[1]), UTF_8));
System.out.println("signature: " + dec.decode(parts[2]).length + " bytes");
}
}Run it with java JwtAnatomy.java on Java 17 or later. The header segment is always eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 for this exact header text, and you will see it at the start of many HS256 tokens. The signature is 32 bytes because SHA-256 produces 32 bytes. An RS256 signature with a 2048-bit key is 256 bytes, which is one reason RS256 tokens are longer.
You can paste any token into a decoder to read it, but doing this in code shows what a library does. It splits on dots, decodes the first two segments, parses JSON, and checks the third.
How Spring Security sees the token
When you configure oauth2ResourceServer(oauth2 -> oauth2.jwt(...)), Spring Security reads the token from the Authorization: Bearer header and passes the string to a JwtDecoder. The default NimbusJwtDecoder uses the Nimbus JOSE library to do these steps in order:
- Parse the compact string. A token without exactly three segments, or with invalid Base64url or JSON, is rejected as malformed.
- Read the header and check that
algis one the decoder accepts. - Select a key, using
kidwhen the key source is a key set, and verify the signature. - Validate the claims. The decoder's validators check timestamps and any issuer or audience rules you added.
- Return a
Jwtobject.
The Jwt object keeps the two parts separate. jwt.getHeaders() returns the header as a Map<String, Object>. jwt.getClaims() returns the payload claims. jwt.getTokenValue() returns the original string. Controllers see the Jwt through @AuthenticationPrincipal, as in the examples later in this tutorial.
A decoder built from a JWK set URI expects RS256 unless you call jwsAlgorithm(...) on the builder. If your authorization server signs with ES256, the default configuration rejects its tokens, even though the signature is valid.
Edge cases and common errors
- Unsecured tokens. The JWS standard allows
"alg": "none", which means no signature. A resource server must never accept it. Spring's decoder requires a signature with an algorithm from its allow-list, sononeis rejected. Do not write custom parsing that skips verification. - Algorithm confusion. If a verifier takes
algfrom the header and picks the key by that value, an attacker can sendHS256and use a public RSA key as the HMAC secret. The fix is to fix the expected algorithm in configuration, as the Nimbus-based decoder does. - Decoding is not verifying. Reading
subfrom a payload you decoded yourself proves nothing. Only a token that passesJwtDecodershould be trusted. - Wrong token type. An ID token is also a JWT, but it is meant for the client, not for your API. If your API accepts it, you may be accepting a token not issued for it. Audience validation, covered later, closes this gap.
- Size. The token travels in every request header. Many servers limit a header to 8 KB. Long role lists and many custom claims can push a token past that limit.
- Opaque look-alikes. Not every bearer token is a JWT. A random string with no dots is an opaque token. A JWT decoder rejects it with a 401. The opaque token chapter covers that case.
Exercise
A token's payload is {"sub":"bob","role":"admin"}. An attacker changes "role":"admin" to "role":"user" for a different user and sends the token back unchanged elsewhere. Why does a correct resource server reject the modified token even though it can read the payload?
Show answer
The signature was computed over the exact header and payload text. Changing the payload changes the signing input, so the signature no longer matches. The attacker cannot produce a new valid signature without the signing key. Readability of the payload is irrelevant, because Base64url is only encoding.
Exercise
Your authorization server signs tokens with ES256. You configure a decoder with NimbusJwtDecoder.withJwkSetUri(uri).build() and every valid token is rejected. What is the likely cause and the fix?
Show answer
The builder expects RS256 by default, so ES256 tokens fail the algorithm check. Call .jwsAlgorithm(SignatureAlgorithm.ES256) on the builder before build().