JWT Authentication — Tokens That Carry Their Own Proof
library-service now runs as three copies behind a load balancer. With server-side sessions, a member who logged in on copy one looks like a stranger to copy two. A JSON Web Token solves this: each request carries a signed token that any copy can check on its own, with no shared session store.
The rule
A JWT is signed, not secret: anyone can read it, only the issuer can forge it.
A JWT is three Base64URL-encoded parts joined by dots: header.payload.signature.
{ "alg": "RS256", "kid": "key-2026" }{
"iss": "https://login.school.example/realms/library",
"sub": "asha",
"aud": "library-service",
"scope": "loans.read books.borrow",
"iat": 1790000000,
"exp": 1790000900
}- The header names the signing algorithm and key.
- The payload holds claims:
iss(issuer),sub(subject, the user),aud(intended audience),exp(expiry time), plus custom ones likescope. - The signature is computed over the first two parts with the issuer's private key (or a shared secret for
HS256).
Base64URL is an encoding, not encryption. Anyone holding the token can decode and read the payload, so never put secrets in it. What they cannot do is change it: editing a single character breaks the signature.
In Spring Boot, the resource-server setup from the previous lesson already does JWT authentication. For each request, it:
- takes the token from
Authorization: Bearer <token>, - verifies the signature with the issuer's public key,
- checks
exp, plusisswhen you setissuer-uriandaudwhen you list the expectedaudiences, - builds an
Authenticationwhose name issuband whose authorities come fromscope.
The server keeps no session, so configure it as stateless:
http.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));The shortcut
To judge any token, run signature, time, audience in that order. A token is trusted only if all three pass.
Signature
Recompute it with the issuer's public key. It matches: nobody altered the payload.
The trade-off of self-contained tokens: they cannot easily be withdrawn before exp. If Asha's token leaks, it stays valid until it expires. That is why access tokens are kept short-lived (minutes, not days), with a separate refresh token to get new ones.
Drills
Answer fast — trust the rule.
What are the three parts of a JWT, in order?
Can someone who intercepts a JWT read the claims inside?
An attacker changes "sub": "asha" to "sub": "admin" in a token. What happens when library-service checks it?
Which claim says when a token stops being valid?
Why are JWT access tokens usually given short lifetimes?
Remember
- A JWT is signed, not secret: anyone can read it, only the issuer can forge it.
- Judge every token by signature, time, audience.
- Trap: long-lived tokens — they cannot easily be taken back.
