What you'll learn: By the end of this lesson you will be able to describe how a request reaches Spring Security (the servlet container,
DelegatingFilterProxy,FilterChainProxy), explain why only the first matchingSecurityFilterChainruns, name what the authentication filters,AnonymousAuthenticationFilter,ExceptionTranslationFilterandAuthorizationFiltereach do, write a request rule and a customAuthorizationManager, add method security and spot the self-invocation hole, and read a captured trace to say which filter handled a request.
A tall office building has a front gate, a lobby desk and a lock on each floor. A visitor walks through them in a fixed order, and each checkpoint can wave the visitor on, send them back to the desk, or end the visit. Spring Security is that layout for a web request: an ordered corridor of small filters, each with one job, in front of your controllers.
This lesson uses Spring Boot 4.1.2 with Spring Security 7.1.2 (the version Boot 4.1.2 pulled into the lab). It assumes Authentication vs Authorization, Sessions vs Tokens. Login flows, OAuth 2 and OpenID Connect, JWT, and RBAC, ABAC and ReBAC are separate lessons in this module (Authentication Flows End to End is the next one).
The core idea
Spring Security is one servlet filter that runs a chosen list of filters. The first SecurityFilterChain whose matcher fits the request picks the list; authentication filters fill in who the caller is, AuthorizationFilter asks an AuthorizationManager whether that caller may do this, and ExceptionTranslationFilter turns a refusal into a 401, a redirect or a 403. Method security repeats the question deeper, on the service method, through a Spring proxy.
Three illustrations run through the lesson:
- Minimal example: one request through the API chain, filter by filter, from the lab's captured trace.
- Realistic example: ShopStream's order and refund API with a store-owner rule and method security, in "In practice".
- Failure example: a refund rule that a bulk endpoint silently skips, because of a Spring proxy rule.
The corridor: from the container to your controller
A servlet container knows about servlet filters, not Spring beans. The reference says DelegatingFilterProxy "allows bridging between the Servlet container's lifecycle and Spring's ApplicationContext" and FilterChainProxy "is a special Filter provided by Spring Security that allows delegating to many Filter instances through SecurityFilterChain". Because FilterChainProxy is a bean, it is typically wrapped in a DelegatingFilterProxy. In Spring Boot you meet none of this wiring: web applications are secured by default once Spring Security is on the classpath, and adding a SecurityFilterChain bean switches that default off.
Figure 1. Where Spring Security sits.
How to read this: "Chain proxy" is FilterChainProxy, the single door. It asks each chain in order whether it matches and sends the request down only the first that does.
The reference puts the rule plainly: "Only the first SecurityFilterChain that matches is invoked".
Two chains, first match wins
The lab defines two chains. This is the API chain, exactly as it is in SecurityConfig:
@Bean
@Order(1)
SecurityFilterChain apiChain(HttpSecurity http) {
http
.securityMatcher("/api/**")
.httpBasic(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable) // no cookies are used for authentication on this chain
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterAfter(new AuditTagFilter(), AnonymousAuthenticationFilter.class)
.authorizeHttpRequests(a -> a
.requestMatchers(HttpMethod.GET, "/api/products").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/stores/{storeId}/**").access(new StoreOwnerAuthorizationManager())
.anyRequest().authenticated());
return http.build();
}
securityMatcher("/api/**") makes it a chain for API paths only. A second chain, webChain, has no matcher and serves everything else with form login, a session and CSRF protection; @Order decides which is tried first. The DSL methods add filters: httpBasic adds BasicAuthenticationFilter, formLogin adds UsernamePasswordAuthenticationFilter, authorizeHttpRequests adds AuthorizationFilter, and addFilterBefore, addFilterAfter and addFilterAt place your own, as the lab does with AuditTagFilter.
The lab asks the real FilterChainProxy for its chains and prints them:
Expected output, captured from a real run (Spring Boot 4.1.2, Spring Security 7.1.2, Java 25 language level, 2026-12-01):
SecurityFilterChain beans, in the order FilterChainProxy tries them:
chain 0 (apiChain), 13 filters:
1. DisableEncodeUrlFilter
2. WebAsyncManagerIntegrationFilter
3. SecurityContextHolderFilter
4. HeaderWriterFilter
5. LogoutFilter
6. BasicAuthenticationFilter
7. RequestCacheAwareFilter
8. SecurityContextHolderAwareRequestFilter
9. AnonymousAuthenticationFilter
10. AuditTagFilter
11. SessionManagementFilter
12. ExceptionTranslationFilter
13. AuthorizationFilter
Expected output, captured from a real run (the same run):
which chain takes which path:
/api/products -> chain 0 (apiChain)
/api/admin/metrics -> chain 0 (apiChain)
/account -> chain 1 (webChain)
/login -> chain 1 (webChain)
Read the list top to bottom as the order of execution: early filters prepare the request (SecurityContextHolderFilter reads the saved security context into the holder), middle filters establish identity, and the last two decide and translate. ExceptionTranslationFilter wraps AuthorizationFilter on purpose, as shown below.
Who is calling: SecurityContext, Authentication, ProviderManager
When a filter such as BasicAuthenticationFilter finds credentials, it builds an Authentication and hands it to an AuthenticationManager, most commonly a ProviderManager, which "delegates to a List of AuthenticationProvider instances", each of which can succeed, fail, or abstain. DaoAuthenticationProvider handles passwords: it "uses a UserDetailsService and PasswordEncoder". The lab's UserDetailsService is Spring's InMemoryUserDetailsManager, which keeps users in memory: right for a lab, wrong for production. By default ProviderManager clears sensitive credentials from the Authentication it returns.
The result goes into the SecurityContextHolder, which "uses a ThreadLocal" by default, and FilterChainProxy makes sure the context is cleared when the request ends. If nobody authenticated, AnonymousAuthenticationFilter puts an anonymous Authentication in the holder, so later code always finds one. The lab's AuditTagFilter writes the type name of whatever the holder contains to a response header: AnonymousAuthenticationToken for an anonymous call, UsernamePasswordAuthenticationToken for a signed-in one.
Is the caller allowed: AuthorizationFilter and AuthorizationManager
AuthorizationFilter is the last filter. It builds a supplier for the Authentication in the holder and "passes the Supplier<Authentication> and the HttpServletRequest to the AuthorizationManager", which "matches the request to the patterns in authorizeHttpRequests, and runs the corresponding rule". A negative decision publishes an AuthorizationDeniedEvent and throws an AccessDeniedException, which ExceptionTranslationFilter handles; a positive one lets the chain continue.
Three rules of the DSL are worth knowing:
- First match wins.
AuthorizationFilterprocesses the rules "in the order listed, applying only the first match". Put narrow rules before broad ones. - End with a catch-all. The reference recommends a final rule such as
anyRequest().denyAll()orauthenticated(), because "any URL that has not already been matched on is denied access", which turns the rule list into an allow list. - Roles carry a prefix. "By default, role-based authorization rules include
ROLE_as a prefix":hasRole("ADMIN")looks for the authorityROLE_ADMIN.
An AuthorizationManager makes the decision. Its authorize method takes the Authentication supplier and the secured object and returns a result; a default verify throws AccessDeniedException on a negative one. AuthorityAuthorizationManager, behind hasRole, returns a positive decision when the Authentication contains any configured authority. When a rule needs more, write your own and plug it in with access(...). This one, from the lab, compares a path variable with the caller's store:
@Override
public AuthorizationResult authorize(Supplier<? extends Authentication> authentication,
RequestAuthorizationContext context) {
Authentication auth = authentication.get();
if (auth == null || !auth.isAuthenticated()) {
return new AuthorizationDecision(false);
}
boolean isOwner = auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_STORE_OWNER"));
String storeId = context.getVariables().get("storeId");
boolean ownsStore = storeId != null && storeId.equals(STORE_OF_OWNER.get(auth.getName()));
return new AuthorizationDecision(isOwner && ownsStore);
}
It returns a decision and never throws. Throwing is the filter's job.
Turning a refusal into a response: ExceptionTranslationFilter
ExceptionTranslationFilter sits just before AuthorizationFilter and calls the rest of the chain inside a try. Per the reference, if the user is not authenticated or the exception is an AuthenticationException, it starts authentication: it clears the holder, saves the request for replay after login, and uses the AuthenticationEntryPoint to request credentials. Otherwise, for an AccessDeniedException, the AccessDeniedHandler runs. Exceptions thrown by AuthorizationFilter or by method security are both caught here.
Figure 2. One refusal, two kinds of answer.
(AuthorizationFilter or method security)"] --> Q{"Authenticated caller
and an AccessDeniedException?"} Q -->|"no"| E["AuthenticationEntryPoint
401 + challenge, or redirect to login"] Q -->|"yes"| H["AccessDeniedHandler
403"]
How to read this: what decides the answer is whether the caller is a real, authenticated user. Anonymous callers are asked to log in; known callers are told no. That is why 401 and 403 differ in this stack, and why a method-security denial also becomes 403.
Method security: the same question deeper in
Request rules see a URL. Many rules need the object: whose order is this, how large is this refund. The Spring Boot starter "does not activate method-level authorization by default", so you add @EnableMethodSecurity, which switches on @PreAuthorize, @PostAuthorize, @PreFilter and @PostFilter. The lab's two examples:
/** Runs first, then the result is checked: the caller must own the order or be support staff. */
@PostAuthorize("returnObject.owner == authentication.name or hasRole('SUPPORT')")
Order find(long id) {
return orders.get(id);
}
/** Checked before the method runs, using the method argument. */
@PreAuthorize("hasRole('SUPPORT') and #amountCents <= 5000")
String refund(long orderId, int amountCents) {
return "refunded " + amountCents + " cents on order " + orderId;
}
Method security is built on Spring AOP: a proxy around the bean calls an interceptor that asks an AuthorizationManager, and a negative answer throws an AccessDeniedException, which ExceptionTranslationFilter turns into 403 when the call came over HTTP. With no HTTP request you handle the exception yourself. Two cautions from the references. First, "unannotated methods are not secured", so keep a catch-all rule in the chain. Second, once a call has reached the target object, calls it makes on itself "are going to be invoked against the this reference, and not the proxy", so self-invocation "will bypass the advice". The same trap bites @Transactional: see Spring @Transactional: Proxy, Rollback, Propagation.
Figure 3. Two layers, one decision maker.
How to read this: both layers ask an AuthorizationManager. A denial from either travels up to "Error mapper", which is ExceptionTranslationFilter, and it writes the response.
Build it: which filter handled the request
This is the minimal example and the failure case together. Goal: send real requests through the real chains and read which chain, filters, rule and component produced each response. Not a network test: requests use Spring's MockMvc, so no port is opened and no Docker is needed; users are in Spring's in-memory user store. The report is built from Spring Security's own TRACE log of each request and from the MVC result.
Setup. From the repository:
cd examples/spring-labs
./gradlew :labs:spring-security-architecture:test
It runs 9 tests, one of which compares the report below with examples/spring-labs/golden/spring-security-architecture.txt. The code is in examples/spring-labs/labs/spring-security-architecture/.
Anonymous and wrong-password calls. With no credentials the chain runs all 13 filters; AuthorizationFilter refuses and ExceptionTranslationFilter hands over to the entry point, which answers 401. A wrong password stops earlier, inside BasicAuthenticationFilter, after 6 of 13 filters.
Expected output, captured from a real run (the same run):
GET /api/admin/metrics, anonymous
chain: apiChain; filters invoked: 13 of 13, last: AuthorizationFilter
request rule: AuthorityAuthorizationManager[authorities=[ROLE_ADMIN]] -> denied
controller reached: no
response written by: ExceptionTranslationFilter -> BasicAuthenticationEntryPoint
Authentication seen by our AuditTagFilter: AnonymousAuthenticationToken
status: 401
GET /api/admin/metrics, alice with a wrong password
chain: apiChain; filters invoked: 6 of 13, last: BasicAuthenticationFilter
controller reached: no
response written by: BasicAuthenticationFilter (credentials rejected) -> BasicAuthenticationEntryPoint
status: 401
A known caller who may not. The same URL as a shopper gives 403, written by the access denied handler.
Expected output, captured from a real run (the same run):
GET /api/admin/metrics, alice (ROLE_SHOPPER)
chain: apiChain; filters invoked: 13 of 13, last: AuthorizationFilter
request rule: AuthorityAuthorizationManager[authorities=[ROLE_ADMIN]] -> denied
controller reached: no
response written by: ExceptionTranslationFilter -> AccessDeniedHandlerImpl
Authentication seen by our AuditTagFilter: UsernamePasswordAuthenticationToken
status: 403
Method security. Order 2 belongs to bob. The request rule only asks for authentication, so alice reaches the controller; the @PostAuthorize rule then refuses the returned order, and the same 403 path writes the response.
Expected output, captured from a real run (the same run):
GET /api/orders/2, alice (order 2 belongs to bob)
chain: apiChain; filters invoked: 13 of 13, last: AuthorizationFilter
request rule: AuthenticatedAuthorizationManager -> granted
method security: Orders.find(long): denied (after the method returned)
controller reached: yes (ApiController.order)
response written by: ExceptionTranslationFilter -> AccessDeniedHandlerImpl
Authentication seen by our AuditTagFilter: UsernamePasswordAuthenticationToken
status: 403
The self-invocation pitfall. The last scenario calls services directly, with no HTTP and no chain. The rule fires for issue, is skipped when bulkIssue calls this.issue, and fires again once the entry point itself carries the annotation.
Expected output, captured from a real run (the same run):
Self-invocation pitfall (RefundDesk, rule: hasRole SUPPORT):
alice calls issue(7): denied -> AuthorizationDeniedException: Access Denied
alice calls bulkIssue([7]), which calls this.issue(7): allowed -> [refund issued on order 7]
alice calls bulkIssueChecked([7]), annotated itself: denied -> AuthorizationDeniedException: Access Denied
sam calls bulkIssueChecked([7]): allowed -> [refund issued on order 7]
Break it. In RefundDesk, delete the @PreAuthorize line above bulkIssueChecked: the pitfall test asserts that alice is refused, so it must fail, and the golden comparison changes too. Restore the line and re-run.
Left out: OAuth resource servers, JWT validation, a database user store, WebSocket and message security, and the web chain's form-login flow beyond what the golden file shows.
Trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| One chain per kind of client | Each chain has only the filters it needs | Matchers and @Order to get right |
Matchers overlap and nobody tests them |
| Request rules only | Visible in one place | See the URL, not the object | The rule depends on who owns the record |
| Method security | Rule travels with the service, works without HTTP | Proxy limits; rules hidden in annotations | Calls go through this |
Custom AuthorizationManager |
Any rule, testable | You own its correctness | A built-in rule already says it |
anyRequest().denyAll() last |
New URLs start closed | One more rule to maintain | Rarely wrong on a public-facing service |
In practice: ShopStream retrofits refund rules
This is the realistic example on ShopStream, the course's running system. It is an educational scenario and every number is an illustrative assumption.
This is a realistic scenario, not a case history.
The situation
ShopStream's Orders service serves the shopper app and the support console. Support staff may refund up to 5,000 cents (illustrative) per order; shoppers may not refund at all. A new bulk endpoint lets support refund many orders at once after a delivery failure.
Starting architecture
Figure 4. The refund path.
How to read this: the chain proves who is calling; the rule that matters, "only support may refund", sits on the service method the controller calls.
Options considered
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
A. Request rule hasRole("SUPPORT") on the refund URLs only |
Visible in the chain | New URLs are unprotected until someone adds a rule | Jobs or other controllers reach the same service |
B. @PreAuthorize on the single-refund method only |
Rule follows the method | The bulk method calls it through this and skips it |
Any wrapper calls it on the same bean |
| C. Annotate every entry point, keep a catch-all, test each as a shopper | Rule holds on every path | Repeated annotations; tests to write | Almost never |
The decision
Option C. Every public method of the refund service that a controller or a job can call carries its own rule, the chain ends with at least anyRequest().authenticated(), and each endpoint has a test that calls it as a shopper and expects a refusal.
Rollout and verification
Ship the single-refund endpoint with its shopper test, then add the bulk endpoint behind the same test. Watch the 403 count per endpoint and the audit log of refunds with the caller's role.
The 2 a.m. failure
Finance reports refunds issued by an account with the shopper role. The single endpoint refuses shoppers, but the bulk method had no annotation and called the checked method on this, as the lab's bulkIssue does, so the rule never ran. First three checks: (1) query the audit log for refunds whose caller lacks the support role; (2) list public methods of the refund service without an authorization annotation; (3) call the bulk path as a shopper in a test and watch it succeed. Mitigation: block the bulk URL with a hasRole("SUPPORT") request rule, then deploy the annotation. Follow-up: one shopper test per path that moves money, and a review rule that no public method of a secured service is unannotated.
Architect's notes
- Draw the chains first. Which paths, which client kind, which credential, in which order; then write the beans.
- End every chain with a deny or an authenticate, so a new controller starts closed.
- Put object-level rules next to the object, in method security or a service check, not in a URL pattern.
- Test the refusals. A test that proves a shopper gets
403is worth more than three that prove staff get200.
Common mistakes
- Assuming two matching chains both run. Only the first does.
- Rules in the wrong order. A broad
authenticated()before a narrowhasRolemakes the narrow rule dead. - Calling a secured method through
this. The proxy never sees the call. - Forgetting
@EnableMethodSecurity. The annotations compile and do nothing.
Key takeaways
- Spring Security is a
FilterChainProxythat runs the filters of the first matchingSecurityFilterChain. - Authentication filters fill the
SecurityContextHolder;AnonymousAuthenticationFiltercovers everyone else. AuthorizationFilterasks anAuthorizationManager; rules are first match wins and should end in a catch-all.ExceptionTranslationFilterturns a refusal into a challenge or redirect for unauthenticated callers and a403for known ones.- Method security works through a proxy: it covers every caller that goes through the proxy and none that call through
this.
Practice exercises
Exercise 1 (30 min). Run the lab. Change /api/products to require authentication and re-run: which golden lines change, and why does the test fail?
Exercise 2 (45 min). Replace the custom manager on /api/stores/{storeId}/** with hasRole("STORE_OWNER") only, then call store 2 as owner1. Explain the difference in one sentence.
Exercise 3 (1 hour). Add a third chain for /internal/** with a custom filter that rejects requests lacking a header. Where should the filter sit, and what does the report show?
Related reading
- Authentication vs Authorization, Sessions vs Tokens: the concepts behind the chain.
- Security for Distributed Systems: the threat-model frame.
- Spring @Transactional: Proxy, Rollback, Propagation: the same proxy rule for transactions.
- API Gateways and Service Meshes: checks at the edge.
- Audit Logging: the record that finds a bypassed rule.
- Authentication and Authorization in the UI: the browser's side of the same refusals.
Official documentation
- Spring Security reference 7.1, Servlet Architecture: filters, chains,
ExceptionTranslationFilter. - Spring Security reference 7.1, Authentication Architecture:
ProviderManager,SecurityContextHolder. - Spring Security reference 7.1, Authorize HttpServletRequests:
AuthorizationFilterand rule order. - Spring Security reference 7.1, Authorization Architecture:
AuthorizationManager. - Spring Security reference 7.1, Method Security:
@EnableMethodSecurityand the annotations. - Spring Framework reference, Proxying Mechanisms: why self-invocation bypasses advice.