Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·50

Spring Security and Modern Identity

Companion to Volume 3, chapter 50: how authentication and authorisation, Spring Security's architecture, modern identity (OAuth 2.0, PKCE, OpenID Connect, JWTs, resource servers, BFFs, service-to-service) and other frameworks connect; new angles (a token as a stamped visitor pass, report mode as a fire drill, a key ring); what the chapter simplifies, measured on the build's stage 51: an API where anyone could read, cancel and accept any order, an access rollout where every one of 124 protected requests in the browser suite would have been refused (all from our own tests) until they carried credentials, a token signed correctly that still meant two things, and browser streams that can't send an Authorization header; the theory behind them (object-level authorisation, parser differentials, ambient credentials, key rotation); how Spring Security reads a bearer token and how it decides a 401 or a redirect, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~11 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 50 covers foundations (authentication against authorisation, where each check lives), Spring Security's architecture (the SecurityFilterChain, authentication internals, passwords, roles and authorities, method security, sessions, CSRF, CORS), modern identity (OAuth 2.0, PKCE, OpenID Connect, JWTs, resource servers, authorisation servers, the BFF pattern, service-to-service) and other frameworks.

foundations Spring Security modern identity where it lives authentication who is calling authorisation what, per object passwords slow hashes, salts keys and secrets rotation, kid SecurityFilterChain filters before MVC AuthenticationManager providers, principals roles, method security @PreAuthorize sessions, CSRF, CORS ambient credentials OAuth 2.0, PKCE delegated access OpenID Connect identity on top JWT, resource server claims you check BFF, service-to-service tokens off the browser browsers cookies, redirects API clients bearer tokens between services client credentials, mTLS other frameworks same ideas, other APIs then proven by and asks feeds plus extended by carried as kept by or or compare builds on: ch12 web security · ch44 backend fundamentals · ch46-48 Spring · ch49 persistence · goes on: ch51 messaging · Vol 7 security exercises: P1–P9 passwords, PKCE, JWT and algorithm confusion, a resource server, two chains, IDOR tests, CSRF and CORS, a BFF, service-to-service; C1–C3
Concept map of chapter 50, Spring Security and modern identity: foundations (authentication against authorisation), Spring Security's architecture (the SecurityFilterChain, authentication, passwords, roles and method security, sessions, CSRF and CORS), modern identity (OAuth 2.0, PKCE, OpenID Connect, JWTs, resource servers, the BFF pattern, service-to-service) and other frameworks, with links such as cookies bringing CSRF and tokens needing every claim checked.

The links worth remembering:

  • Authentication says who; authorisation says what, per object. Most real breaches of APIs are the second: a valid user reaching someone else's data (OWASP's API Security Top 10 puts broken object-level authorisation first).
  • Every credential is carried somehow, and the carrier decides the attacks. Cookies travel automatically (so CSRF matters); bearer tokens travel only when code adds them (so theft and storage matter).
  • Tokens are claims you check, not facts you receive. Signature, algorithm, issuer, audience, expiry, and what the claims mean, every time.

Explain it differently

1. A token is a stamped visitor pass. The desk stamps your name, your floor and today's date on it. A guard checks the stamp, the date and the floor: not your face, and not what you say. A pass with two floors written on it, both under a genuine stamp, should be turned away, not read generously (Gaps 3).

2. Report mode is a fire drill. Before locking the doors for real, you sound the alarm and count who's still inside and where. TiffinBox counted 124 requests that would have been locked out, all its own (Gaps 2).

3. Keys are a key ring. New locks accept the new key and, for a while, the old one; you take the old key off the ring once nobody's using it. Rotation without that overlap locks everyone out at once (Gaps 4).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12 and the build's stage 50 and 51 servers (exp/51), unless stated.

1. "Add authentication" isn't the work; deciding per object is. Until stage 51, TiffinBox believed X-Customer-Id. What that allowed, with customer c1's order o1 at kitchen k7:

Terminal
# stage 50
c2 places an order as c1 (X-Customer-Id: c1)              201
nobody (no credentials) reads c1's order                  200  {"id":"o1","kitchenId":"k7","status":"Placed", …
kitchen k3 accepts k7's order                             200  {"id":"o1","kitchenId":"k7","status":"Accepted", …
c2 cancels c1's order                                     200  {"id":"o1","kitchenId":"k7","status":"Cancelled", …

Order ids are sequential (o1, o2, …), so anyone could read every order by counting. Stage 51 signs tokens (tiffinbox token DIR customer c1), and one class (Access) holds every rule: a customer sees and cancels their own orders, a kitchen sees and moves its own, an admin anything. With the same calls, enforced:

Terminal
# stage 51, auth=enforce
c2 places an order as c1 (X-Customer-Id: c1)              403  {"title":"Not allowed","status":403,"detail":"customer c2 can't order as c1"}
nobody (no credentials) reads c1's order                  401  this needs a token
c2 reads c1's order                                       404  no such order
kitchen k3 accepts k7's order                             404  {"title":"No such order","status":404,"detail":"no such order"}
c2 cancels c1's order                                     404  …
c1 reads its own order                                    200  …
kitchen k7 accepts its own order                          200  …

Someone else's order is a 404, not a 403: a 403 would confirm that o1 exists, and with sequential ids that's a count of the business's orders. The checks need the order's owner, which TiffinBox kept only in the log's first record; stage 51 indexes it (Orders.customerOf). Authentication was 60 lines; knowing whose each object is was the design.

2. Turning access control on breaks your own clients first. Stage 51 starts in report mode: every decision is made, and a denial is written to the access log instead of returned. The browser suite against it, before its clients carried credentials:

Terminal
# report mode, before
GET /kitchen/{k}                      46 requests,    46 would be refused
GET /kitchens/{k}/stream              21 requests,    21 would be refused
GET /orders/{id}                       3 requests,     3 would be refused
POST /orders                          45 requests,    45 would be refused
POST /orders/{id}/events               9 requests,     9 would be refused
all                                  124 requests,   124 would be refused (124 401 no token)
# after: the suite's API calls carry bearer tokens, its browsers a session cookie; the servers enforce
all                                  124 requests,     0 would be refused

Every one came from TiffinBox's own tests; the release check and Main simulate needed tokens too (simulate now mints one per simulated customer). This is stage 49's deprecation again: measure, move the clients, then switch. A team that enabled enforcement directly would have learned the same list from a failed deploy.

3. A correctly signed token can still be ambiguous. The lab's alg: none attack fails here (only HS256 is accepted, whatever the header says). A subtler one: claims are JSON, and JSON parsers disagree about duplicate keys. A token whose claims say "role":"customer","role":"admin", signed with the real key (by a buggy issuer, or an issuer whose parser takes the first value while ours took the last):

Terminal
as issued                                            accepted as customer c1
claims changed to role admin, old signature          refused: bad signature
alg none, no signature                               refused: only HS256 tokens are accepted
signed, with "role" twice (customer, then admin)     refused: unreadable claims: duplicate key "role" at offset 30
signed for another service (aud)                     refused: not for this service

TiffinBox reads claims with stage 49's strict JSON reader, so the token is refused rather than resolved. Most JSON libraries take the last value silently (Jackson does by default); if the issuer's took the first, the two services disagree about the role. Checking aud stops a token issued for one service being replayed at another that trusts the same keys.

4. The browser decides how credentials travel. The kitchen screens open an EventSource for the live stream, and EventSource can't send an Authorization header. So browsers carry a cookie: POST /session with a token sets tb_session (HttpOnly, SameSite=Strict), sent with every same-origin request, the stream included. The kitchen views' code didn't change at all; the cookie made every one of their requests authenticated. Cookies are sent automatically, which is what CSRF exploits; TiffinBox's stage 12 check (state-changing requests only from its own origin, by Fetch Metadata or Origin) and SameSite=Strict both stop it. API clients use bearer tokens, which travel only when code adds them. One server, two carriers, each chosen by what the client can do. Verifying costs little:

Terminal
verify: 1.6 us per token (200,000 tokens)

Common misconceptions

Misconception What's actually true Where it's shown
"Logged-in users can only see their own data." Only if every object lookup checks ownership. Gaps 1
"403 is the honest answer." For objects, 404 avoids confirming they exist. Gaps 1
"Turn on security, then fix what breaks." Report first; the breakage is measurable in advance. Gaps 2
"A valid signature means valid claims." Claims can be ambiguous, for another audience, or expired. Gaps 3
"Tokens belong in headers." Browsers' EventSource, images and navigations only send cookies. Gaps 4
"Rotating a key logs everyone out." Not if old keys still verify until their tokens expire. Theory 4

Theoretical gaps: the ideas behind the chapter

1. Object-level authorisation. Route-level rules ("customers may GET /orders/{id}") are necessary and not sufficient; each object needs an owner and a check against the caller. Put the rules in one place, test them as a matrix (role × action × ownership), and make "no rule" mean "deny".

2. Parser differentials. When two components parse the same bytes differently (duplicate keys, Unicode normalisation, number precision, header folding), an attacker can say one thing to the checker and another to the user of the result. Refuse ambiguity at the boundary instead of resolving it.

3. Ambient credentials. Cookies, client certificates and network position are attached by the platform, not by the code making the request, so any request the platform makes carries them: the root of CSRF and of server-side request forgery. Explicit credentials (bearer tokens) can't be borrowed that way, but can be stolen from wherever code keeps them.

4. Key rotation. A key identifier (kid) in each token lets verifiers hold several keys: add the new key, make it the signing key, keep the old one until every token it signed has expired, then remove it. Removing a key is also how you revoke every token it signed, at once.

Applying it

Code walkthrough

Gaps 4 and Spring's side of it: how a bearer token is found, and why an unauthenticated browser gets a login redirect while an API client gets a 401. From spring-projects/spring-security, main at commit 11cb88e (19 November 2026).

Finding the bearer token

oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java:

Java
	private boolean allowFormEncodedBodyParameter = false;

	private boolean allowUriQueryParameter = false;
	...
	public @Nullable String resolve(final HttpServletRequest request) {
		return resolveToken(
			resolveFromAuthorizationHeader(request),
			resolveAccessTokenFromQueryString(request),
			resolveAccessTokenFromBody(request)
		);
	}
	...
			else if (token != null) {
				BearerTokenError error = BearerTokenErrors
					.invalidRequest("Found multiple bearer tokens in the request");
				throw new OAuth2AuthenticationException(error);
			}

Three places a token may come from (RFC 6750): the Authorization header, an access_token query parameter, a form body. The last two are off by default: a token in a URL ends up in access logs, browser history and Referer headers. That's exactly what an EventSource would need (Gaps 4), so Spring makes you turn it on knowingly; TiffinBox uses a cookie instead. And two tokens in one request are an error, not a choice: the same refusal of ambiguity as Gaps 3.

A redirect for people, a 401 for programs

config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java:

Java
	protected final RequestMatcher getAuthenticationEntryPointMatcher(B http) {
		...
		MediaTypeRequestMatcher mediaMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy,
				MediaType.APPLICATION_XHTML_XML, new MediaType("image", "*"), MediaType.TEXT_HTML,
				MediaType.TEXT_PLAIN);
		mediaMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
		RequestMatcher notXRequestedWith = new NegatedRequestMatcher(
				new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
		return new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher));
	}

With form login, an unauthenticated request is redirected to the login page only if it asks for HTML (or plain text, or an image) explicitly, ignoring */*, and isn't marked as an XHR; everything else gets the API answer. TiffinBox does the same with less: a GET whose Accept names text/html gets 303 /login, anything else a 401 problem with WWW-Authenticate: Bearer. It's chapter 48's content negotiation again, applied to "who are you?".

Debugging drills

D1. Customers see each other's orders

A support ticket: a customer changed the number in an order URL and saw someone else's order. Every endpoint requires login.

D2. The deploy that locked out the kitchens

After enabling authorisation, every kitchen tablet showed errors, though the API tests passed.

D3. An admin who isn't

An audit finds requests performed with admin rights by a user whose account has only the customer role. Signatures all verify.

D4. Everyone logged out at 10:00

Rotating the token signing key logged every user out at once.

Career-oriented

Interview prep

Mid-level 1: 401 or 403

Question. "When should an API return 401, 403 or 404 for an access problem?"

How to get there. What does the client need to do next in each case, and what does each reveal?

Mid-level 2: where the token goes

Question. "Our single-page app keeps its access token in localStorage. Is that a problem?"

How to get there. Who can read localStorage, and what are the alternatives?

Senior 1: adding authorisation to a live system

Question. "A service with many clients has no authorisation. Plan adding it without an outage."

How to get there. Measure first, then move clients, then enforce.

Senior 2: tokens or sessions

Question. "Should our web app use JWTs or server-side sessions?"

How to get there. What does each make easy and hard: revocation, scaling, size, browsers?

Staff 1: one identity across services

Question. "Twelve services each check tokens differently. Design the standard."

How to get there. What must every service check, and how will you know they do?

Staff 2: when security work is done

Question. "How do you know an access-control project is finished, and stays finished?"

How to get there. What signals keep working after the project ends?