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));