Authentication: Basic, API keys, session cookies and JWT
Basic auth, API keys, session cookies with the right security flags, where to keep tokens in a browser, JWT anatomy and pitfalls, refresh token rotation, token revocation, passkeys (WebAuthn) and Spring Security 7 on Spring Boot 4.
On this page
1. The problem
A SPA stores a 30-day JWT in localStorage. A compromised npm package ships the tokens of 12,000 users off to an attacker. "Log out" does nothing: the tokens have 29 days left and the server has no way to revoke them.
2. Key idea
Every post-login credential is a bearer credential: whoever holds it can use it. Two questions decide safety: can JavaScript read it, and does the server keep state to revoke it? A session id is a parking ticket, with the car in the lot; a JWT is a stamped name badge anyone can read, and the guard only checks the stamp.
| Kind | Server keeps | Revocation | Where it usually breaks |
|---|---|---|---|
| Session cookie | the whole session | instant | missing cookie flags, id not rotated on login |
| JWT | only the signing key | needs extra state | no aud check, algorithm chosen by the token, stored in localStorage |
| Passkey | a public key | delete the credential | the recovery path when a device is lost |
2.1 Which to choose?
| Approach | Use when | Don't use when |
|---|---|---|
| Session + Redis | a monolithic web app, a few services trusting one store | many teams and services without a shared store |
| Short access JWT + rotating refresh | many services, mobile, an existing auth server | a single web app: extra traps for no gain |
BFF + HttpOnly cookie |
SPAs that must call token-protected APIs | |
| Passkeys (WebAuthn) | replacing passwords for end users | machine to machine |
2.2 JWT and refresh-token traps
alg: none, algorithm confusion: let the token pick the algorithm and an attacker switches RS256 to HS256 and signs with the public key. The server pins the algorithm.- Signature-only checks: a valid signature proves who issued the token, not that it's meant for you. Check
aud. - Rotating refresh tokens: each use invalidates the old token; a used token showing up again revokes the whole family. You need a grace period of a few tens of seconds, or a network drop while receiving the response logs real users out.
3. In Spring Security 7 (Spring Boot 4)
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.securityMatcher("/api/**")
.csrf(c -> c.disable()) // safe only because the credential is a Bearer header, not a cookie
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
return http.build();
}
// application.properties
// spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.dev
// spring.security.oauth2.resourceserver.jwt.audiences=booking-api
// spring.security.oauth2.resourceserver.jwt.jws-algorithms=ES256
// token aud=notification-api -> 401; alg none -> 401; expired 2 minutes ago -> 401Sessions for web: server.servlet.session.cookie.name=__Host-SID, http-only=true, secure=true, same-site=lax, Spring Session with Redis. A hand-written login must call securityContextRepository.saveContext(...). Passkeys: http.webAuthn(...).
Where to keep credentials in the browser
HttpOnly cookie |
sessionStorage | localStorage | |
|---|---|---|---|
| Sent automatically | yes | no | no |
| Readable by JavaScript | no | yes | yes |
| Main risk | CSRF (blocked by SameSite, CSRF tokens) |
XSS | XSS, lives forever |
Anything JavaScript can read, XSS can read too. SPAs should go through a BFF (backend for frontend): the BFF holds tokens, the browser only has a __Host- HttpOnly cookie. Logging in must rotate the session id to block session fixation.
4. Working with AI
Give the AI: the SecurityFilterChain, MockMvc tests for 401/403/tampered tokens, migrating old .and() config to the lambda DSL.
Check in AI-written code:
- The algorithm is pinned on the server, never read from the token's
alg. -
audis checked, not just the signature andexp. - No tokens in
localStorage; session cookies haveHttpOnly,Secure,SameSite. - Refresh tokens are stored hashed and rotated, with tests for reuse detection and the grace period.
5. Exercises
Exercise 1: An AI-written JwtDecoder
The AI says "secure: ES256 is pinned, signature and expiry are checked". The same auth server also issues tokens for notification-api.
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder
.withJwkSetUri("https://auth.example.dev/.well-known/jwks.json")
.jwsAlgorithm(SignatureAlgorithm.ES256)
.build();
}Find the bug, name a test that proves it, fix it.
Solution to Exercise 1
Neither iss nor aud is checked: a token issued for notification-api has a valid signature and hasn't expired, so booking-api accepts it.
Test: sign a token with aud = notification-api using a test key in a fake JWKS, call /api/flights, expect 401; the code above returns 200.
Fix: decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefaultWithIssuer(issuer), new JwtClaimValidator<List<String>>("aud", aud -> aud.contains("booking-api")))), or just use the issuer-uri + audiences properties.
Exercise 2: Mass logouts
After enabling refresh-token reuse detection, "randomly logged out" tickets go from 5 to 300 a day, 80% from Android on 4G. Logs show reuse detected 1–3 seconds after a successful refresh, same device, same IP. Attack or design bug?
Solution to Exercise 2
A design bug: the app loses the network while receiving the response; the server has already marked r1 used and issued r2, the client never got it and resends r1, and the whole family is revoked. Two SPA tabs refreshing at once do the same.
15 minutes: switch reuse detection to log-only with a feature flag. Root fix: a grace period of a few tens of seconds that returns the same r2; the client runs one refresh at a time. Mark tokens used with UPDATE ... WHERE token_hash = ? AND used_at IS NULL and check the row count.
Summary
- 401 is unauthenticated, 403 is missing permission.
- Session cookies with all four flags, id rotated at login.
- JWT: pin the algorithm, check
iss,aud,exp. - Short access tokens + rotating refresh tokens with a grace period.
- No tokens in
localStorage; SPAs use a BFF.
Read more: Spring Security for REST APIs.
Practice interview questions on this topic
- How do authentication and authorization differ, and what about 401 vs 403?
- How do cookies, sessions and tokens differ?
- When do you choose session cookies vs JWT, and are sessions really hard to scale?
- Where should a SPA store tokens, and which flags should a session cookie have?
- How do you revoke a JWT before it expires and design “log out of all devices”?
- How do encoding, hashing, encryption and signing differ? Is a JWT payload secret?
Comments
Community rules