Skip to content

    System Design

    JWT: Structure and Pitfalls

    Read a JWT part by part, learn the algorithm and key checks a verifier must make, and test none, algorithm confusion, rotation and revocation in a Spring lab.

    By Published 13 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: OAuth 2.0, OpenID Connect and PKCE

    What you'll learn: By the end of this lesson you will be able to take a JWT apart into header, payload and signature and say what the signature does and does not protect, explain why the verifier, not the token, must choose the algorithm, describe the none and algorithm-confusion attacks and the configuration that stops them, rotate a signing key with kid and a JWK Set without rejecting live tokens, set clock skew, and say what revocation costs for a token that is valid until it expires. A Spring Security lab runs each attack against a deliberately naive verifier and against a strict one.

    A JWT is a postcard with a tamper-evident seal. Anyone who handles it can read every word; the seal does not hide the message, it shows whether a word was changed after the sender sealed it. Two mistakes follow: writing something private on the card, and letting the card say which seal to check. If the card says "no seal needed" and the reader believes it, anyone can write a card.

    The previous lesson, OAuth 2.0, OpenID Connect and PKCE, showed where JWT access tokens come from and the checks an API runs. This lesson opens the token itself: its structure, the algorithm and key rules, and the failures those checks prevent. The browser-side partner is Token storage and secure cookies; JWTs, single sign-on and the session lifecycle covers how a client lives with expiry and sign-out. The sessions-versus-tokens choice is in Authentication vs Authorization, Sessions vs Tokens.

    Verified with Spring Boot 4.1.2, Spring Security 7.1.2, Java 25, RFC 7515, 7517, 7519, 8725, 9068, 7009 and 7662 and the Spring Security reference, on 2026-12-01.

    The core idea

    1. A JWT is three encoded parts, and only the third is secret-dependent. The header and payload are readable by anyone; the signature proves they have not changed since the issuer signed them.
    2. The verifier decides the algorithm and the key, never the token. A header that picks its own algorithm is how none and algorithm-confusion attacks work.
    3. A signed token cannot be recalled. Rotation, skew and revocation are decisions about time and state around a token that is otherwise valid until exp.

    Structure: three parts

    RFC 7519 says a JWT is "a sequence of URL-safe parts separated by period characters" and that JWTs are always the JWS Compact Serialization or the JWE Compact Serialization. A signed JWT (a JWS, RFC 7515) is:

    BASE64URL(header) . BASE64URL(payload) . BASE64URL(signature)

    The signature is computed over the signing input: the encoded header, a period and the encoded payload, exactly as sent. The encoding is base64url without padding: an encoding, not encryption. A JWT can instead be encrypted (a JWE), which hides the claims; this lesson is about signed tokens.

    flowchart LR accTitle: How a signed JWT is built accDescr: The header JSON and the payload JSON are each base64url encoded. The two encoded strings joined by a period form the signing input. The signing input is signed with the private key, and the base64url of the signature is the third part. The three parts joined by periods form the token. H["Header JSON: alg, kid, typ"] --> HE["base64url"] P["Payload JSON: claims"] --> PE["base64url"] HE --> SI["signing input = header.payload"] PE --> SI SI --> SIG["sign with private key"] SIG --> SE["base64url"] HE --> T["token = header.payload.signature"] PE --> T SE --> T

    Figure 1. Where the three parts come from. How to read this: the signature is made from the first two parts and nothing else. Changing one character of either encoded part makes the signature fail, which is the only protection a signed JWT offers.

    The header names the algorithm (alg, which RFC 7515 says MUST be present), may name the key (kid) and may declare the type (typ). The payload holds claims. RFC 7519 defines the registered ones: iss (issuer), sub (subject), aud (audience), exp (expiration), nbf (not before), iat (issued at) and jti (a unique identifier). The lab decodes a token with no key at all:

    Expected output, captured from a real run (Spring Boot 4.1.2, Spring Security 7.1.2, Java 25, 2026-12-01):

    == 1. The three parts of a token, decoded with no key
    header    {"kid":"key-1","typ":"at+jwt","alg":"RS256"}
    payload   {"sub":"alice","aud":"https://api.shop.example","scope":"orders:read","iss":"https://id.example","exp":1796116200,"iat":1796115600,"jti":"demo-jti-1"}
    signature 256 bytes (RS256, 2048-bit key)
    signing input = the first two parts as sent, joined by a period; the signature covers exactly that
    unchanged token: accepted sub=alice scope=orders:read
    scope edited from orders:read to orders:write, old signature kept: rejected: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature

    That is illustration 1, the minimal example: the claims are readable without any key, and an edited scope with the old signature is refused. Because the claims are readable, a JWT must never carry a secret.

    Choosing an algorithm and key

    With a symmetric algorithm such as HS256 one secret both signs and verifies, so every service that can verify a token could also mint one. With an asymmetric algorithm such as RS256 the authorization server signs with a private key that never leaves it and every API verifies with the public key. For tokens that many APIs check, that keeps minting power in one place, and it is what Spring Security's decoder trusts by default: "by default, NimbusJwtDecoder, and hence Resource Server, will only trust and verify tokens using RS256". RFC 8725 adds that applications MUST only allow cryptographically current algorithms and warns that low-entropy symmetric keys are weak.

    The rule that holds the whole lesson together is RFC 8725 section 3.1: a library MUST let the caller specify the set of supported algorithms, and each key MUST be used with exactly one algorithm. The Spring lab's strict decoder is that rule in code:

    // The application, not the token, decides which algorithm is acceptable: only RS256, only keys from our source.
    processor.setJWSKeySelector(new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, keys));
    // RFC 9068 and RFC 8725 section 3.11: only a token that declares itself a JWT access token (typ at+jwt) is accepted.
    processor.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("at+jwt")));

    Pitfall 1: the none algorithm

    RFC 7519 defines an Unsecured JWT as one whose alg is none, with an empty signature, for content secured by other means. RFC 9068 is blunt for access tokens: the resource server "MUST reject any JWT in which the value of alg is none". The attack is to send a token whose header says none to a verifier that obeys the header.

    Pitfall 2: algorithm confusion

    RFC 8725 section 2.1 names a second attack: a verifier that lets the header choose the algorithm and then uses the key it was handed. The server publishes its public key so anyone can verify. An attacker sets alg to HS256 and computes an HMAC over the token using the public key's bytes as the secret. A naive verifier sees HS256, uses "the key" as an HMAC secret, and the forgery verifies. The cure is the same rule: the verifier fixes RS256, so an HS256 token is refused before any key is used.

    case "none" -> {
        return parts.payload(); // mistake 1: believes a token that says it needs no signature
    }
    case "HS256" -> {
        // mistake 2: any key the verifier was handed is used with whatever algorithm the token asks for,
        // so the public RSA key becomes the shared secret of an HMAC that anyone can compute.

    This is the heart of NaiveVerifier, insecure on purpose: it lives in src/test so it cannot be shipped and must never be copied into real code. Both forged tokens carry a textbook-benign payload (sub mallory, scope orders:write).

    Expected output, captured from a real run (the same run):

    == 2. The none algorithm: a token that says it needs no signature
    forged token header {"alg":"none","typ":"at+jwt"}, empty signature
    naive verifier (the header picks the algorithm): ACCEPTED, payload {"iss":"https://id.example","sub":"mallory","aud":"https://api.shop.example","scope":"orders:write","exp":1796116200}
    strict decoder (RS256 only): rejected: Unsupported algorithm of none
    
    == 3. Algorithm confusion: the public key used as an HMAC secret
    the public key is published at the jwks_uri, so the attacker has it; header {"alg":"HS256","typ":"at+jwt","kid":"key-1"}
    naive verifier (the header picks the algorithm): ACCEPTED, payload {"iss":"https://id.example","sub":"mallory","aud":"https://api.shop.example","scope":"orders:write","exp":1796116200}
    strict decoder (RS256 only): rejected: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) found

    This is illustration 3, the failure case: the naive verifier accepts both forgeries and the strict decoder refuses both, because the token's header never widens what it accepts.

    Pitfall 3: trusting other header fields

    Header parameters are attacker input until the signature has passed against a key you chose. RFC 8725 section 3.10 notes that kid is used to look up keys, so applications should ensure it creates no SQL or LDAP injection, and says applications SHOULD protect against attacks through jku and x5u, which point at a key location the token supplies. RFC 7515 says an embedded jwk is only as good as the way its origin is authenticated. The safe pattern is the lab's: kid selects among keys from a source you configured, and an unknown key is rejected, never fetched from where the token says.

    Keys and rotation with kid

    Keys must change, on a schedule or after a leak. A JWK Set (RFC 7517) is a JSON object with a keys array, so it can hold several keys, and kid is used "to choose among a set of keys within a JWK Set during key rollover"; different keys SHOULD use distinct kid values. Rotation is therefore: publish the new key, start signing with it, keep the old key published while tokens signed with it can still be live, then remove it.

    sequenceDiagram accTitle: Rotating a signing key with an overlap accDescr: The authorization server publishes key-1. It rotates: it starts signing with key-2 and publishes both. A resource server with a stale cache rejects a new token until it refreshes the key set. Old tokens still verify while key-1 is published. After key-1 is retired and the cache refreshes, tokens signed with key-1 are rejected. participant AS as Authorization server participant RS as Resource server (cached keys) AS->>RS: publishes key-1 RS->>RS: caches [key-1] AS->>AS: rotate: sign with key-2, publish [key-1, key-2] AS->>RS: token B (kid key-2) RS-->>AS: unknown kid: reject until the cache refreshes RS->>RS: refresh cache: [key-1, key-2] AS->>RS: token A (kid key-1, unexpired) and token B RS-->>AS: both accepted (overlap) AS->>AS: retire key-1, publish [key-2] RS->>RS: refresh cache: [key-2] AS->>RS: token A (kid key-1) RS-->>AS: rejected

    Figure 2. A rotation with an overlap. How to read this: the resource server only knows the keys in its cached copy. A new key causes rejections until the cache refreshes; a retired key causes rejections for every unexpired token signed with it.

    Spring's reference says a resource server by default "caches in-memory the authorization server's JWK set for 5 minutes"; it does not say what happens to a token with an unknown kid, so do not assume a refresh happens for you. The lab models the cache with JwkCache, whose refresh() copies the published set:

    public void refresh() {
        this.snapshot = authorizationServer.publicJwkSet();
    }

    Expected output, captured from a real run (the same run):

    == 4. Key rotation with kid: the resource server keeps a cached copy of the JWK Set
    published kids [key-1], token A signed with key-1: accepted sub=alice scope=orders:read
    authorization server rotates: signs with key-2, publishes [key-1, key-2]
    token B (key-2) before the resource server refreshes its cache: rejected: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) found
    token B after the cache refresh: accepted sub=alice scope=orders:read
    token A (still unexpired, key-1 still published): accepted sub=alice scope=orders:read
    key-1 retired, published kids [key-2], cache refreshed; token A: rejected: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) found
    token B: accepted sub=alice scope=orders:read

    The lab shows the mechanism, not a policy. The policy is arithmetic: keep the old key published for at least the longest lifetime of a token signed with it, plus the skew, plus the time a resource server may keep a stale cache.

    Clock skew

    RFC 7519 says the current time MUST be before exp and at or after nbf, and that implementers MAY allow "some small leeway, usually no more than a few minutes" for clock skew. Spring's reference says a resource server configures 60 seconds by default. The lab moves its clock around exp for a 600-second token.

    Expected output, captured from a real run (the same run):

    == 5. Expiry and clock skew (token lifetime 600 s, clock moved by hand)
    skew 0 s:
      exp -1 s: accepted
      exp +0 s: accepted
      exp +1 s: rejected
      exp +59 s: rejected
      exp +60 s: rejected
      exp +61 s: rejected
    skew 60 s:
      exp -1 s: accepted
      exp +0 s: accepted
      exp +1 s: accepted
      exp +59 s: accepted
      exp +60 s: accepted
      exp +61 s: rejected
    nbf -61 s (skew 60 s): rejected
    nbf -59 s (skew 60 s): accepted

    A skew of 60 seconds extends every token's life by 60 seconds. Also, in this run Spring's validator accepted a token at exactly exp (exp +0 s) with no skew, while RFC 7519 words the rule as "before"; the difference is one second at the boundary and any skew hides it.

    Revocation: the price of a stateless token

    A signed token is checked without asking the issuer, so the issuer cannot cancel it. RFC 7009 says that for self-contained tokens the resource server need not contact the authorization server, so immediate revocation takes backend interaction no standard defines. Three options exist.

    flowchart TD accTitle: Choosing how to cut access early accDescr: If access must end within the token lifetime and a short lifetime is acceptable, rely on short lifetimes and refresh token revocation. If it must end sooner, either add a deny-list on the token id at each API, or use opaque tokens introspected at the authorization server. start["Must a token stop working before exp?"] --> no{"Is the token lifetime short enough?"} no -- "Yes" --> short["Short lifetime, revoke the refresh token"] no -- "No" --> state{"Can every API reach shared state?"} state -- "Yes" --> deny["Deny-list on jti, kept until exp"] state -- "No or want one source of truth" --> intro["Opaque tokens, introspection (RFC 7662)"]

    Figure 3. Three ways to shorten the window. How to read this: each option moves some state back into the system. The deny-list needs every API to read a shared set; introspection needs a call to the authorization server.

    1. Short lifetimes and refresh. RFC 7009 says that when a refresh token is revoked the server SHOULD also invalidate access tokens based on the same grant if it supports that; otherwise they "will not be immediately invalidated". A short lifetime caps the window.
    2. A deny-list on jti. Each API checks the token's jti against a set of revoked identifiers kept until the tokens would have expired. It works, but the shared set is state every API must read, which is what a session store was.
    3. Opaque tokens with introspection. RFC 7662 defines an active response, and Spring's reference says introspection "can be handy when revocation is a requirement". Caching the answer reopens a window in which a revoked token still works.

    Expected output, captured from a real run (the same run):

    == 6. Revocation: a signed token stays valid until exp unless the verifier looks something up
    token demo-jti-6 before revocation: accepted sub=alice scope=orders:read
    the authorization server revokes it; the resource server has no deny-list yet: accepted sub=alice scope=orders:read
    after the resource server adds demo-jti-6 to its deny-list: rejected: An error occurred while attempting to decode the Jwt: the token has been revoked

    The other side of this topic

    Where a browser keeps the token is Token storage and secure cookies; the client's view of expiry and sign-out is JWTs, single sign-on and the session lifecycle. Those decide who can steal a token; this lesson decides what a server believes once it holds one. The front-end lab token-session-lifecycle models the client's clocks; this lab is the verifier's side.

    Build it: a strict decoder against a naive one

    Goal: run each pitfall against a verifier that has it and one that does not. Not a real identity provider: keys come from a locally generated KeyRing, the signing side of a stand-in authorization server; the JWK Set cache is an in-memory model; no HTTP, no Docker. The strict decoder is Spring Security's real NimbusJwtDecoder.

    cd examples/spring-labs
    ./gradlew :labs:jwt-validation-pitfalls:test

    It runs 6 tests, five behaviour tests and one that compares the report with examples/spring-labs/golden/jwt-validation-pitfalls.txt. The code is in examples/spring-labs/labs/jwt-validation-pitfalls/. The clock is moved by hand and keys are never printed, so the report is the same on every run.

    Break it. In StrictJwtDecoder.build, remove new RevocationValidator(revokedJtis) from the DelegatingOAuth2TokenValidator; the revocation scenario and its test fail, because a revoked token is accepted again. Restore the line and re-run. Left out: a real JWKS endpoint over HTTP and its caching headers, encrypted JWTs, ECDSA and EdDSA keys, and opaque-token introspection.

    Trade-offs

    Choice Gain Cost Wrong when
    Asymmetric signing (RS256) Only the issuer can mint; any API verifies Larger tokens, key distribution One service issues and verifies, and a shared secret is simpler
    Longer overlap when rotating Fewer rejected tokens A leaked old key stays trusted longer The old key was compromised
    Deny-list on jti Early revocation without a server call Shared state on the hot path You cannot run a fast shared store
    Opaque tokens Revocation is current A call per request or a cache The API must work when the issuer is down

    In practice: ShopStream rotates its signing key

    This is illustration 2, the realistic example, an educational scenario on the course's running example, ShopStream; it describes no real company. Every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's authorization server signs access tokens with one RSA key, to be rotated every quarter and at once after any suspected leak. Three APIs verify tokens, each with a cached copy of the JWK Set. Access tokens live 10 minutes. A rotation must not return a wave of 401 responses.

    Starting architecture

    Starting point: one signing key, three verifying APIs with cached keysAuthorization server to JWK Set (publishes); JWK Set to Orders API (fetched, cached); JWK Set to Billing API; JWK Set to Stock APIAuthorization server: signs with key-1Authorizationserversigns with key-1JWK Set: published keysJWK Setpublished keysOrders API: cached key setOrders APIcached key setBilling API: cached key setBilling APIcached key setStock API: cached key setStock APIcached key setpublishesfetched, cached

    Figure 4. One key, three caches. How to read this: every API holds its own copy of the published keys. The authorization server cannot change what a cache holds; it can only change what it publishes.

    Options considered

    Option Behaviour Risk
    A. Swap the key in place Publish only the new key at once Every unexpired token fails; stale caches fail new tokens
    B. Overlap Publish both, sign with the new, retire the old later A short period where two keys are trusted
    C. Emergency cut Retire the old key at once after a leak Live tokens fail, accepted to stop the leak

    The decision

    Option B for the quarterly rotation, with a computed retire time: token lifetime (10 minutes) plus skew (1 minute) plus cache time (5 minutes) is 16 minutes, rounded up to 30 (illustrative). Option C is the written procedure for a leak, at the cost of forcing everyone to sign in again.

    Rollout and verification

    A rehearsal runs the lab's scenario against the real verifier configuration: publish both keys, check that a token from the new key is accepted after a cache refresh, retire the old key, check that an old token is refused. In production the checks are invalid_token counts by API, the kid of accepted tokens and the age of each API's cached key set.

    The 2 a.m. failure

    The page reads: new sign-ins fail on the Billing API but not the others, 4 minutes into a rotation. Its cache refreshes less often than the others after a config change, so it does not know key-2 and rejects every token that carries it. The checks are the kid of a rejected token, the age of the Billing API's cached set and what the server publishes. The mitigation is to force a key set refresh on that API. The lasting fix is to start a rotation only when every API's cache age is under the overlap time, and to alert on unknown-kid rejections that outlast a cache lifetime.

    Architect's notes

    • Fix the algorithm in configuration, never in the token. One key, one algorithm.
    • Treat a header as input until the signature passes. kid selects among keys you hold; it never fetches one.
    • Compute the rotation overlap. Token lifetime plus skew plus cache time, plus margin.
    • Say what revocation means before shipping. If the answer is "the token lifetime", write that down.

    Common mistakes

    • Letting the token choose the algorithm. That is both none and algorithm confusion.
    • Retiring the old key the moment the new one signs. Every unexpired token fails.
    • Assuming the cache refreshes on an unknown kid. Spring's reference does not say it does.
    • A huge skew "to be safe". It is added to every token's life.
    • Acting on claims before verifying. Decode for logging, never for decisions.

    Key takeaways

    • A JWT is base64url header, payload and signature; anyone can read the first two, and the signature covers exactly the encoded pair.
    • The verifier fixes the algorithm and the key source; each key is used with one algorithm. none and algorithm confusion both rely on a verifier that obeys the header.
    • kid selects among keys in a JWK Set, which makes rotation with an overlap possible.
    • Skew is a small grace period after exp and before nbf.
    • A signed token is valid until exp unless the verifier looks something up; revocation moves state back into the system.

    Practice exercises

    Exercise 1 (20 min). Decode a JWT from your own tooling with base64url and list three things it reveals that a user may not expect.

    Exercise 2 (45 min). Run the lab. In scenario 4, retire key-1 before the first cache refresh and say which tokens fail and for how long. Then compute the retire time for 15-minute tokens, 2 minutes of skew and a 10-minute cache.

    Exercise 3 (1 hour). Run "Break it" and describe in one paragraph why a verifier that accepts two algorithms for one key is unsafe.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments