Backend security series: 1. Encoding, hashing, encryption and signatures · 2. Storing passwords and encrypting personal data · 3. Web attacks and the OWASP Top 10 · 4. Authentication: sessions, cookies and JWT · 5. Authorization, SSO and OAuth2
This post answers “who is calling the API?” with Basic auth, API keys, session cookies and JWT. Afterwards you can choose between sessions and JWTs, and know how to store, revoke and rotate tokens. “What may they do?” is part 5; read part 1 first (encoding, HMAC, digital signatures).
1. Identity, authentication and authorization
Key idea: authentication proves “I am X”; authorization decides what X may do. Two jobs, two status codes.
- Identity: what uniquely identifies a subject: a user id, an email, a client id.
- Authentication: proving identity with a password, an OTP, a certificate or a trusted token.
- Authorization: what X may do with which resource.
At the airport, showing your ID at security is authentication; showing your boarding pass at the gate is authorization.
2. Basic auth and API keys
Key idea: Basic auth sends the password on every request and only suits internal tools over TLS. An API key is a random secret for machine-to-machine calls; the server stores only its hash.
2.1. Basic auth
The client sends Authorization: Basic base64(username:password) on every request. Without the header the server replies 401 with WWW-Authenticate: Basic realm="api", and the browser pops up a login dialog.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: GET /reports
S-->>C: 401 + WWW-Authenticate Basic
C->>S: GET /reports + Authorization Basic dXNlcjpwYXNz
S->>S: Decode Base64, check password with bcrypt
S-->>C: 200 + data
Base64 is encoding, not encryption. The real limits: the raw password travels on every request, the server runs a (deliberately slow) password hash on every request, and there’s no logout. Fine for internal tools or service-to-service calls over TLS, not for end users.
2.2. API keys
An API key is a long random string sent in Authorization: Bearer ... or X-API-Key. It’s a bearer secret: whoever holds it can use it, like a house key with no name on it.
API key design and how it compares with OAuth2 client credentials
- Generate with
SecureRandom, at least 128 bits, with a readable prefix (sk_live_,sk_test_) so secret scanners can recognise it. - Store only a hash (SHA-256 is enough because the key already has high entropy; no need for a slow password hash, see part 2), plus the first few characters for lookup and display.
- Attach a scope, an owner and an expiry; let two keys be valid at once for a while so rotation has no downtime.
- If you need tamper or replay protection, a key isn’t enough; sign the body with HMAC plus a timestamp, as payment gateways do (part 1).
3. Session cookies
Key idea: the server keeps the session data; the browser only holds a random ID in a cookie. Deleting the session on the server logs the user out immediately, the biggest advantage over JWT.
3.1. The flow and the cookie flags
After login the server creates a session (user id, creation time…) and sends the session ID in a cookie; the browser sends the cookie back automatically and the server looks the session up by ID.
sequenceDiagram
participant B as Browser
participant S as Server
participant R as Session store
B->>S: POST /login
S->>R: Create session for user 42
S-->>B: Set-Cookie SID=random, HttpOnly, Secure, SameSite=Lax
B->>S: GET /orders + Cookie SID
S->>R: Look up session by SID
S-->>B: 200 + orders
| Attribute | Effect |
|---|---|
HttpOnly |
JavaScript can’t read the cookie |
Secure |
Sent only over HTTPS |
SameSite=Lax / Strict |
Not sent when the request originates from another site (mitigates CSRF) |
__Host- prefix |
Browser accepts it only with Secure, Path=/ and no Domain: subdomains can’t overwrite it |
CSRF is a foreign page making your browser send a request with your real cookie; XSS is a foreign script running inside your page. The slides say session cookies are “vulnerable to XSS and CSRF”. More precisely: with HttpOnly, XSS can’t read the session ID; SameSite blocks most CSRF and a CSRF token blocks the rest (part 3).
You need both an idle timeout (15–30 minutes of inactivity) and an absolute timeout (8–12 hours even while active); with idle only, a stolen session kept “warm” lives forever. A password change kills every session.
3.2. Are sessions really hard to scale?
The slides say sessions are “stateful, hence hard to scale”. Only true when sessions live in each instance’s RAM; Spring Session + Redis lets every instance share them, at one Redis read under 1 ms per request. Moving sessions into the database with Spring Session JDBC, limiting sessions and remember-me are covered in the Spring Session and remember-me post.
4. Where to keep credentials in the browser
Key idea: anything JavaScript can read, XSS can read too. Web apps should keep tokens on the server (a BFF) and give the browser only an HttpOnly cookie.
| Cookie | sessionStorage | localStorage | |
|---|---|---|---|
| Size | ~4 KB per cookie | ~5 MB | ~5–10 MB |
| Lives until | Server sets Expires/Max-Age |
Tab closes | Explicitly cleared |
| Sent automatically | Yes | No | No |
| Readable by JavaScript | No, if HttpOnly |
Yes | Yes |
A BFF (Backend for Frontend) is a thin backend in front of the SPA: it holds the tokens server-side, gives the browser a session cookie, and attaches the access token when calling the API. It’s the IETF’s current recommendation for browser-based apps; native mobile apps keep tokens in the Keychain/Keystore.
5. Token-based auth and JWT
Key idea: a JWT is a self-contained, signed token: the server checks the signature and expiry without a store lookup. The signature prevents tampering but hides nothing; the server pins the algorithm itself.
5.1. Anatomy
The client sends the token in Authorization: Bearer ...; no cookie needed, so it works for mobile and web alike. A JWT has three Base64url parts: header.payload.signature.
- Header:
{"alg":"ES256","typ":"JWT","kid":"2026-11"}, the algorithm and which key signed it. - Payload: the claims (fields of information). The seven registered claims of RFC 7519:
iss(issuer),sub(subject),aud(intended service),exp(expiry),nbf(not before),iat(issued at),jti(token ID); plus public claims (email,scope) and private ones (tenant_id). - Signature: a signature over
base64url(header) + "." + base64url(payload).
Choosing a signing algorithm, three slide corrections and minor traps
- JWTs are usually signed, not encrypted. The common form is JWS: anyone can read the payload. The diagram where the “server decrypts the token” is wrong; the server verifies the signature. To hide the content use JWE, or simply keep sensitive data out of the token.
- “Recommended: AES” doesn’t apply to JWT signatures. AES is symmetric encryption. The signing algorithms are HS256 (HMAC-SHA256), RS256/PS256 (RSA), ES256 (ECDSA) and EdDSA.
- The sample payload has
iat= 1516239022 (2018) andexp= 1311281970 (2011): the token expired before it was issued, and a correct library rejects it.
Three minor traps:
- A weak HS256 secret can be brute-forced offline from one captured token; use 256 random bits.
- Stuffing in hundreds of permissions makes the token several KB and can exceed a proxy’s header limit.
kidshould only select from a set of known keys.
5.2. Signing and verifying HS256 by hand
Issuing is just b64(header) + "." + b64(payload) followed by the HMAC-SHA256 of that string. Verifying: pin the algorithm, compare signatures in constant time, read claims only after the signature checks out, then check iss, aud, exp with clock skew.
HS256 JWT verifier with javax.crypto and its test run
A minimal version with javax.crypto, to show there’s nothing magic about JWT (in production use a library such as Nimbus JOSE + JWT). The Java code in this post was run on JDK 21.
String verify(String token) {
String[] parts = token.split("\\.", -1);
if (parts.length != 3) throw new SecurityException("malformed");
if (!decode(parts[0]).contains("\"alg\":\"HS256\"")) throw new SecurityException("unexpected alg");
byte[] expected = hmacSha256(parts[0] + "." + parts[1]);
if (!MessageDigest.isEqual(expected, B64URL_DEC.decode(parts[2]))) // constant-time comparison
throw new SecurityException("bad signature");
String payload = decode(parts[1]); // read claims only AFTER the signature checks out
if (!issuer.equals(claim(payload, "iss"))) throw new SecurityException("bad iss");
if (!audience.equals(claim(payload, "aud"))) throw new SecurityException("bad aud");
if (clock.instant().minus(SKEW).isAfter(Instant.ofEpochSecond(numClaim(payload, "exp"))))
throw new SecurityException("expired");
return claim(payload, "sub");
}
Running it with a 15-minute token: the valid token returns user-42; a changed sub with the old signature, alg: none, the wrong aud, and 16 minutes later are all rejected; 20 seconds past expiry (inside the 30-second skew) still passes.
5.3. JWT pitfalls
6. Refresh tokens and revocation
Key idea: access tokens live briefly, and revocation moves to a stateful refresh token on the server. Revoking faster than the TTL requires added state: a denylist, a token version or a sid.
6.1. Rotation and reuse detection
Access tokens live 5–15 minutes; refresh tokens live long, are stored hashed on the auth server, go only to the refresh endpoint, and rotate: each use invalidates the old one and returns a new one.
Every refresh token from one login belongs to a family. An already used token showing up again means two parties hold it; the server can’t tell which is genuine, so it revokes the whole family.
The rotate function, test run and grace period
synchronized String rotate(String presented) {
Row row = byHash.get(sha256(presented)); // store the hash only, never the raw token
if (row == null || row.revoked()) throw new SecurityException("invalid refresh token");
if (row.used()) { // an old token is being reused: revoke the family
revokeFamily(row.familyId());
throw new SecurityException("reuse detected");
}
byHash.put(sha256(presented), row.markUsed());
return mint(row.familyId(), row.userId()); // new refresh token, same family
}
Test run: rotating r1 to r2 works, replaying r1 reports “reuse detected”, and afterwards r2 is rejected too. In production, replace synchronized with UPDATE refresh_token SET used_at = now() WHERE token_hash = ? AND used_at IS NULL and check the affected row count.
6.2. Ways to revoke a JWT
| Approach | Mechanism | Revocation delay | Cost |
|---|---|---|---|
| Short TTL | Wait for expiry, revoke the refresh token | Up to the TTL | Nothing extra |
jti denylist |
Revoked jti in Redis, TTL = remaining lifetime |
Immediate | A Redis lookup per request |
| Token version | ver claim compared to the user’s token_version |
Immediate for the whole user | A version lookup (cacheable) |
| Session-bound token | sid claim pointing at a server-side session |
Immediate | Back to being stateful |
The last row is the slides’ “embed session into token” suggestion; typically sid is checked only for sensitive operations. The “security levels of tokens” suggestion maps to the acr/amr claims (was MFA used?): sensitive APIs demand a higher level or force re-authentication.
7. Spring Security 6
Key idea: a session-based web app sets the cookie flags and adds Redis; a JWT API is a resource server (a service that validates tokens itself): pin the algorithm, check aud. The Spring Boot 3 upgrade trap: the SecurityContext is no longer saved to the session automatically.
Tested labs for both sides live in their own posts: a session web app with the filter chain and UserDetailsService in form login with Spring Security, and a stateless API that issues and validates JWTs in Spring Security for REST APIs.
Session config, JWT resource server and the SecurityContext trap
The Spring Security 6 configuration below has not been run inside a real application. A session-based web app (Spring Boot 3):
server.servlet.session.timeout=30m
server.servlet.session.cookie.name=__Host-SID
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=lax
Adding spring-session-data-redis moves sessions into Redis. Fixation protection (changeSessionId) is on by default.
An API that accepts JWTs (a resource server):
@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
.requestMatchers(HttpMethod.GET, "/api/flights/**").hasAuthority("SCOPE_flights:read")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())); // scope -> SCOPE_xxx by default
return http.build();
}
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder decoder = NimbusJwtDecoder
.withJwkSetUri("https://auth.example.dev/.well-known/jwks.json")
.jwsAlgorithm(SignatureAlgorithm.ES256) // pin the algorithm
.build();
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer("https://auth.example.dev"), // iss + exp/nbf, 60s skew
new JwtClaimValidator<List<String>>("aud", aud -> aud != null && aud.contains("booking-api"))));
return decoder;
}
NimbusJwtDecoder fetches and caches the JWKS, picks the key by kid, and refetches on an unknown kid, so keys rotate without redeploying services. Mapping claims to permissions and RBAC is in part 5.
8. Case study: web and mobile, 15-minute access, log out everywhere
Key idea: 15-minute access JWTs + rotating refresh tokens + a token version give revocation within 30 seconds while services still verify tokens locally.
Problem: a booking app with an SPA, a mobile app and three backend services. Access tokens live at most 15 minutes; “log out of all devices” or a password change must take effect within 1 minute; mobile shouldn’t ask for login again for 30 days if used regularly.
Why not a single mechanism: sessions only means all three services call the auth store; 30-day JWTs only can’t be revoked.
Case study: detailed design, failure modes and access token TTL
Design:
- The auth service issues 15-minute ES256 access tokens with
sub,aud,scope,ver; services verify via JWKS. - Refresh tokens rotate as in section 6.1, with a 30-day sliding expiry and a 90-day absolute one.
- Mobile keeps the refresh token in the Keychain/Keystore; the web goes through a BFF, and the browser only holds a
__Host-HttpOnlycookie. - “Log out everywhere”: revoke all the user’s families and bump
users.token_version; services cache the version for 30 seconds and reject tokens with an olderver.
Failure modes: if the version store is down, fail open for read APIs and fail closed for money-moving APIs. Clock drift causes random exp/nbf failures, so keep NTP in sync.
Exercises
Exercise 1: Write an HS256 JWT verifier
Task (paraphrased): sign and verify HS256 JWTs without a JWT library; reject a tampered payload, alg: none, the wrong aud and expired tokens; allow a little clock skew.
Solution to Exercise 1
The code is in section 5.2. The decisive points: split("\\.", -1) so an empty signature part isn’t dropped; pin the algorithm; compare signatures with MessageDigest.isEqual before trusting any claim. A senior would add: parse JSON with a real library, check nbf, cap the token length.
Exercise 2: Refresh token rotation with reuse detection
Task (paraphrased): design the table and the rotate function: store hashes only, rotate on every use, revoke the whole chain on reuse.
Solution to Exercise 2
The function is in section 6.1. Table refresh_token(token_hash PK, family_id, user_id, used_at, revoked_at, expires_at) with an index on family_id. Mark a token used with UPDATE ... WHERE token_hash = $1 AND used_at IS NULL AND revoked_at IS NULL: one affected row means valid; zero rows means look it up again to tell “doesn’t exist” from “reused” (the SQL wasn’t run against a real database).
Remember
- Explain how 401 differs from 403 and how a client should react.
- Name the four session cookie flags and why the session ID must change on login.
- Explain why tokens in localStorage are dangerous and how a BFF fixes it.
- List the JWT verification steps (pinned algorithm, signature,
iss/aud/exp) and why algorithm confusion happens. - Know when to pick sessions or JWTs, and the four ways to revoke a JWT.
Interview questions
Junior
How does authentication differ from authorization?
Authentication verifies who you are; authorization decides what you may do.
Missing or bad credentials get 401 with WWW-Authenticate; authenticated but not permitted gets 403.
Is Basic auth secure?
Only acceptable over TLS for internal tools or service-to-service calls, because Base64 is just encoding.
Over HTTPS nobody reads it on the wire, but the raw password travels with every request and there’s no logout.
What are the parts of a JWT? Is the payload secret?
Three Base64url parts: header, payload, signature. The payload isn’t secret; anyone holding the token can read it.
The header has the algorithm and kid; the payload has claims like iss, sub, aud, exp; the signature only prevents tampering. Keep sensitive data out of the payload.
Mid
Which flags should a session cookie have, and why?
HttpOnly, Secure, SameSite=Lax/Strict and the __Host- prefix.
HttpOnly so scripts can’t read it, Secure so it only travels over HTTPS, SameSite to mitigate CSRF, __Host- so subdomains can’t overwrite it. Add idle and absolute timeouts, and change the session ID on login to block session fixation.
Are sessions really hard to scale?
No, only when sessions live in each instance’s RAM.
Spring Session + Redis lets every instance share them; the real cost is the dependency on Redis.
Where should an SPA keep its tokens?
Not in localStorage; best is a BFF that keeps tokens on the server while the browser only has an HttpOnly cookie.
One XSS bug is enough to steal tokens from localStorage. Without a BFF, keep the access token in memory and the refresh token in an HttpOnly cookie scoped to the refresh endpoint.
How do refresh token rotation and reuse detection work?
Each refresh marks the old token used and issues a new one in the same family; if a used token shows up again, the whole family is revoked.
A reused token means two parties hold it. You need a short grace period for clients that lost the response.
Senior
How do you revoke a JWT before it expires?
You have to add state; typically a short TTL for most APIs and a state check for sensitive ones.
The options: a short TTL plus refresh token revocation; a jti denylist in Redis; a per-user token_version; or a sid claim pointing at a server-side session.
What is JWT algorithm confusion and how do you prevent it?
The attacker switches alg from RS256 to HS256 and signs with the public key as the secret; prevent it by pinning the algorithm on the server.
An RS256 public key is available to everyone, and a generic verify call accepts such a token. Pin the algorithm and key type on the server (e.g. NimbusJwtDecoder.jwsAlgorithm(...)), never read alg from the token, and reject none.
When do you choose sessions and when JWTs?
A monolith or a few services trusting one store: session + Redis. Many services, several client types, a dedicated auth server: short-lived JWTs.
Session + Redis gives instant revocation and fewer traps. With JWTs: short-lived, asymmetrically signed access tokens verified via JWKS, plus stateful refresh tokens.
Design “log out of all devices” in a JWT-based system
Revoke all of the user’s refresh token families and bump their token_version; services reject access tokens with an older ver.
Services cache the version for a few dozen seconds. The revocation delay equals the cache time, not the TTL.
Useful phrases for interviews
- “A 401 means we don’t know who you are; a 403 means we know, and the answer is no.”
- “An API key is a bearer secret, so we store only its hash and scope it narrowly.”
- “We rotate the session ID on login to shut down session fixation.”
- “Sessions scale fine once they live in Redis; the real trade-off is revocation versus a shared dependency.”
- “A JWT is signed, not encrypted, so nothing sensitive goes in the payload.”
- “The server pins the algorithm; the token never gets to choose it.”
- “A valid signature tells you who issued the token, the audience claim tells you it’s meant for you.”
- “Access tokens are short-lived and refresh tokens rotate, so a stolen refresh token gets detected on reuse.”
- “In the browser, tokens stay behind a backend-for-frontend and the page only sees an HttpOnly cookie.”
- “Log out everywhere is a token-version bump, so the revocation delay is our cache TTL, not the token TTL.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.