Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Security › Authentication

JWT structure and verification

How does the server trust a token that anyone can read?

Why it exists — The server session approach keeps the login state in server storage and looks it up with the session ID on every request, so if there are several servers, or several services have to check the same login, they all have to share that storage. A JWT writes the user information and a signature into the token itself, so any server that has only the key for checking the signature can verify on its own that the token is exactly as it was issued.

Where it's used today — The ID token in OpenID Connect is a JWT, and a JWT is also commonly used for the access tokens that an OAuth 2.0 authorization server issues. The side that calls the API sends the token in the Authorization: Bearer header, and on a Spring server, the OAuth2 resource server feature of Spring Security checks the signature and the expiration time with a JwtDecoder (usually NimbusJwtDecoder). If you need a logout or an account suspension to take effect right away, you use server sessions or keep the lifetime of the token short.

A JWT is a string made of three parts joined by dots (.): a header, a payload, and a signature. The first two parts are not encrypted. They are only written in a different notation, so anyone can read and change them. The decode(token) method of the JwtDecoder that Spring Security provides checks the algorithm, the signature, and the expiration time in that order, throws an exception if even one of them is wrong, and returns the contents only when all of them are correct. You see where decode throws what when the token is changed or time has passed.

Checked against real execution · The 24 combinations were decoded with the real NimbusJwtDecoder (Spring Security 7.1.1, nimbus-jose-jwt 10.9.1), and the results, the exception names and messages, and the 60 second expiration margin were checked. The 200 and 401 responses of a Spring Boot 4.1.1 resource server that uses the same decoder were also checked. The verification times were confirmed in two ways, a run with the clock of JwtTimestampValidator fixed and a run with the system clock, and the code of "What the decoder does inside" was run as it is on JDK 21

Concepts in this lab

JSON Web Token (JWT)
A token that carries content such as user information (claims) and has a signature attached. It has three parts: a header, a payload, and a signature. The server verifies the signature to confirm that the token was not forged, and it does not need to look up a separate store. The payload is encoded, not encrypted, so anyone can read its contents. Do not put sensitive information in it.
Base64url encoding
Where it's used today — It is used to write byte values that go straight into a URL, such as a token sent in an address or the code_challenge value of OAuth PKCE. In Java, you create it with Base64.getUrlEncoder().withoutPadding().
A notation that writes bytes using only uppercase and lowercase English letters, digits, and the characters - and _. It is Base64 with + and / replaced by - and _ and the trailing = removed, so that the result can be put in a URL or an HTTP header without breaking. All three parts of a JWT are written in this notation. Anyone can turn it back into the original contents without a key, so it is not encryption and does not hide the contents at all.
Claim
A name/value pair written in the payload of a token. Some names are defined by the standard, such as sub (who the token is about), exp (the expiration time), and iss (who issued it), and some are added by a service because it needs them, such as role. exp is written in seconds counted from midnight (0:00) on January 1, 1970 (UTC), and the server accepts the token only while the current time is before exp (a margin of a few tens of seconds is sometimes allowed for clock differences between servers). Claims can be read by anyone, so you do not put sensitive values such as passwords in them, and you do not trust their contents before the signature has been verified. In Spring Security, you take them out of a Jwt object that has finished verification with getSubject(), getExpiresAt(), and getClaimAsString("role").
JwtDecoder and NimbusJwtDecoder
Why it exists — Verifying a JWT requires getting everything right: decoding base64url, fixing the algorithm, calculating the signature and comparing in constant time, key length, and the expiration time and clock skew. If you write it yourself, missing just one place lets a forged token pass. Spring leaves this work to a well-tested library and provides an interface that returns only the result, as a Jwt object and fixed exceptions.
Where it's used today — In Spring Boot, if you register a JwtDecoder as a bean and turn on http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())), BearerTokenAuthenticationFilter calls decode on every request and answers with 401 if it fails. To check iss or aud too, you pass a validator made with something like JwtValidators.createDefaultWithIssuer to setJwtValidator.
JwtDecoder is an interface that Spring Security (spring-security-oauth2-jose) provides, and with one method, Jwt decode(String token), it verifies the text of a token and turns it into a Jwt object. If verification fails, it throws an exception of the JwtException family. If the format, the algorithm, or the signature is wrong, it throws BadJwtException, and if the signature is correct but a validation rule such as the expiration time fails, it throws JwtValidationException, which inherits from BadJwtException. NimbusJwtDecoder is the default implementation that does this work with the Nimbus JOSE+JWT library. You build one for a symmetric key (HS256) with NimbusJwtDecoder.withSecretKey(key).build(), for a public key with withPublicKey(key), and for the key-list address of an authorization server with withJwkSetUri(uri). The default validator (JwtValidators.createDefault()) checks the typ header and the expiration and start times, and it allows a 60 second margin on the expiration time.
HMAC and digital signatures
Why it exists — If you send only a hash value, someone in the middle can change the content, compute a new hash, and attach it, so the forgery cannot be noticed. HMAC and digital signatures attach a value that can be created only with a key, so the receiving side can tell apart a message modified by a party that does not have the key.
Where it's used today — They are used for the signature of a JWT (HS256 is HMAC, RS256 is a digital signature), for signatures sent in a request header as with GitHub webhooks, and for verifying HTTPS certificates.
Techniques for confirming that a message was not changed on the way and that the legitimate party sent it. HMAC hashes the message together with a secret key that both sides share to produce an authentication code. With a digital signature, the sender signs with a private key and the receiver verifies with the public key. Only the signer can create the signature, so the sender cannot deny having sent the message.
Algorithm verification
Where it's used today — When you build a decoder that verifies a JWT, you fix the algorithm to accept, such as HS256 or RS256. This also blocks the attack in which alg is changed to HS256 on a server that verifies with a public key, so that the public key is used as if it were a secret key.
The practice of having the server, not the token, decide which signature algorithm is used to verify a token. The header of a JWT has an item called alg that says which algorithm was used to sign it, but the header is text that anyone can change. If the server simply follows this value, the sender can change alg to none (no signature) and make the server skip the signature check. So the server decides the algorithm it accepts in advance, and if the alg in the header is different from it, it rejects the token before even calculating the signature. NimbusJwtDecoder.withSecretKey(key) of Spring Security builds a decoder that is set to HS256 (you can change it with macAlgorithm), and it rejects a token whose alg is none with a BadJwtException that says "Unsupported algorithm of none".
Clock skew
Why it exists — Even if clocks are set with NTP, each server drifts a little. If you compare without a margin, a short-lived token that was just issued can be rejected at once as expired on a server whose clock is ahead of the issuing server.
Where it's used today — It is used by a resource server that verifies JWT access tokens and by a client that checks an OpenID Connect ID token. If the lifetime of the token is very short, you shrink the margin by the same amount.
Clock skew is the margin of a few seconds to a few minutes that a verifier allows when it compares the expiration time (exp) or the start time (nbf) of a token, on the assumption that the clocks of the server that issued the token and the server that verifies it can differ a little. RFC 7519 Section 4.1.4 allows such a margin. JwtTimestampValidator of Spring Security allows 60 seconds by default, and rejects a token with "Jwt expired at …" when the time 60 seconds before now is after exp. So a token 30 seconds past exp still passes, and it is rejected only after 61 seconds have passed. You can change the margin by creating one such as new JwtTimestampValidator(Duration.ofSeconds(10)).

Try these

Running with the default settings

  1. Someone changed the middle part of the token before sending it. They rewrote the role from USER to ADMIN and left the original signature at the end as it was.
  2. decoder.decode(token): the decoder cuts the token at the dots (.) into three parts and decodes the first part (the header) with base64url. No key is needed. The result is {"alg":"HS256","typ":"JWT"}. The alg is what the token says about itself: "this token was signed with this algorithm."
  3. Decoding the second part (the payload) the same way gives {"sub":"7","role":"ADMIN","exp":1767225600}. It is not encrypted, only written in a different notation, so anyone who gets hold of the token can read it. The signature has not been checked yet, so this content is not trusted.
  4. Algorithm check: when this decoder was built with withSecretKey(key), it was set to HS256 (the default). The alg in the header is also HS256, so it goes on to check the signature with the server's key.
  5. Recalculating the signature: the decoder recalculates HMAC-SHA256 from the first two parts of the received token and the key only the server knows. The result is _Crl3waj…. The server does not trust the signature that came with the token. It builds one itself.
  6. Comparison: it compares the recalculated value (_Crl3waj…) with the third part of the token (5hho4Bt2…). They differ. The attached signature was made from the contents before the change, so it does not match the value calculated from the changed contents. It throws BadJwtException. The message is "An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature".
  7. Rejected: an exception occurred, so the contents of the token are not used. With the resource server setting (oauth2ResourceServer), BearerTokenAuthenticationFilter receives this exception and answers with 401 and a WWW-Authenticate: Bearer error="invalid_token" header.

Result of this run

Code

// Part of a server code made as an example (class declaration, serverKey field, and imports omitted)
// JwtDecoder, NimbusJwtDecoder, Jwt, BadJwtException, and JwtValidationException are
// provided by Spring Security (spring-security-oauth2-jose).
// Request header  Authorization: Bearer <token>
// Token  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
//       .eyJzdWIiOiI3Iiwicm9sZSI6IkFETUlOIiwiZXhwIjoxNzY3MjI1NjAwfQ
//       .5hho4Bt2LLsypoE43dqORdbPqUDkMlzinRCY-zDKmMc
// Verification time  2025-12-31 23:50:00 UTC   (exp = 2026-01-01 00:00:00 UTC)

SecretKey key = new SecretKeySpec(serverKey, "HmacSHA256");        // a key only the server knows (32 bytes)
JwtDecoder decoder = NimbusJwtDecoder.withSecretKey(key).build();   // accepted algorithm: HS256 (the default)

try {
    Jwt jwt = decoder.decode(token);   // checks in the order algorithm → signature → expiration (60 second skew)
    String userId = jwt.getSubject();             // "7"
    String role = jwt.getClaimAsString("role");   // "USER"
} catch (JwtValidationException e) {   // the signature matched but a check such as expiration failed
    // do not use the contents of the token
} catch (BadJwtException e) {          // the algorithm or the signature is wrong   // ← this token: Invalid signature
    // do not use the contents of the token
}

// In a Spring Boot server, you do not call decode yourself. If you register this decoder as a bean and turn on
// http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())),
// BearerTokenAuthenticationFilter calls decode on every request and answers with 401 if an exception occurs.

Assumptions of this model

The token text and the signature values on the screen were each actually created in our test run with javax.crypto.Mac (HmacSHA256) of JDK 21 and with crypto of Node.js 24, and I confirmed that the same values come out. The 12 cases (four tokens and three verification times) were decoded with the real NimbusJwtDecoder (spring-security-oauth2-jose of Spring Security 7.1.1 and nimbus-jose-jwt 10.9.1), and I confirmed that the results and the exception names and messages are the same as on the screen. JwtTimestampValidator measures with the system clock, so the cases were run in two ways. In one, the token text on the screen was decoded as it is by a decoder that has a JwtTimestampValidator whose clock is fixed with setClock to the verification time on the screen (the verification times on the screen are values chosen for this lab). In the other, a decoder that is exactly the code on the screen (system clock) decoded tokens newly created with an expiration time 10 minutes after, 30 seconds before, and 5 minutes before the time of the run. The decisions of the two runs were the same. I also confirmed by running that a token passes up to 60 seconds after exp and is rejected from 61 seconds after, and that a token 30 seconds past exp is rejected when a validator with the margin reduced to 10 seconds is passed to setJwtValidator. The same decoder was registered as a bean on a Spring Boot 4.1.1 server with oauth2ResourceServer turned on, and requests carrying the 12 tokens were sent to it. I confirmed that the response is 200 when the token passes, and 401 with the header WWW-Authenticate: Bearer error="invalid_token" when it is rejected. The standard code on the screen was confirmed to compile with javac together with the real libraries, and the code of "What the decoder does inside" was run as it is on JDK 21 and gave the same decisions as the real decoder. The standards behind this are as follows. The shape of three parts joined by dots and the base64url notation are in RFC 7515 Section 3 and Section 2, that the signature is calculated over "first part.second part" is in RFC 7515 Section 5.1, the meaning of exp and that a clock skew can be allowed are in RFC 7519 Section 4.1.4, the shape of a token whose alg is none and whose signature is empty is in RFC 7519 Section 6.1, and the recommendation that the server set the algorithms it accepts is in RFC 8725 Section 3.1. A real server may also add validators so that other claims such as iss and aud are checked. The keys and tokens on the screen are values made for this lab. A server that uses a public-key algorithm (RS256) and the attack on it are not covered.

Previous lab: Password hashing · Next lab: OAuth login flow

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these