The security filter chain
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A guest asks for order 14 and gets 401. Which of the many checks said no, and why did it not reach the controller? The answer is a line of small steps that every request passes, in a fixed order.
Servlet filters: code that runs before the controller
A servlet filter is a class that Tomcat calls for a request before the servlet (in Spring, the DispatcherServlet and then your controller). It may pass the request on or answer by itself.
The plain Java program below copies the idea with no Spring at all: a logging filter, an authentication filter that may stop the request, and a controller at the end.
Example 1 · A filter chain in plain Java
import java.util.List;import java.util.Map;
record Request(String method, String path, Map<String, String> headers) {}
/** One step before the controller. It may pass the request on, or answer by itself and stop. */interface Filter { String doFilter(Request request, Chain chain);}
/** Calls the filters one after another, then the controller at the end. */class Chain { private final List<Filter> filters; private int position = 0;
Chain(List<Filter> filters) { this.filters = filters; }
String proceed(Request request) { if (position < filters.size()) { Filter next = filters.get(position++); return next.doFilter(request, this); } return controller(request); }
private String controller(Request request) { System.out.println(" controller runs for " + request.path()); return "200 OK"; }}
class LogFilter implements Filter { public String doFilter(Request request, Chain chain) { System.out.println(" LogFilter: " + request.method() + " " + request.path()); String status = chain.proceed(request); // run the rest of the chain System.out.println(" LogFilter: answered " + status); return status; }}
class AuthFilter implements Filter { public String doFilter(Request request, Chain chain) { if (!request.headers().containsKey("Authorization")) { System.out.println(" AuthFilter: no Authorization header, stopping here"); return "401 Unauthorized"; // the controller never runs } System.out.println(" AuthFilter: header found, passing on"); return chain.proceed(request); }}
public class FilterChainDemo {
static void handle(Request request) { System.out.println(request.method() + " " + request.path()); List<Filter> filters = List.of(new LogFilter(), new AuthFilter()); String status = new Chain(filters).proceed(request); System.out.println("Client gets: " + status); System.out.println(); }
public static void main(String[] args) { handle(new Request("GET", "/api/v1/orders/14", Map.of())); handle(new Request("GET", "/api/v1/orders/14", Map.of("Authorization", "Basic ZGV2OnNlY3JldA=="))); }}GET /api/v1/orders/14
LogFilter: GET /api/v1/orders/14
AuthFilter: no Authorization header, stopping here
LogFilter: answered 401 Unauthorized
Client gets: 401 Unauthorized
GET /api/v1/orders/14
LogFilter: GET /api/v1/orders/14
AuthFilter: header found, passing on
controller runs for /api/v1/orders/14
LogFilter: answered 200 OK
Client gets: 200 OKWhat this code does
Chain.proceedcalls the next filter, and after the last one the controller. A filter that returns without callingproceedends the request there.- For the first request
AuthFilterstops the chain: the controller never runs, butLogFilterstill logs the 401 on the way back. - Spring Security works the same way, only with real
jakarta.servlet.Filterobjects and many more filters.
Example 2 · src/main/java/com/shoplite/lab/common/RequestLogFilter.java
Runs in: the security-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.common;
import java.io.IOException;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;
/** A plain servlet filter: runs before the controller and logs each request it sees. */@Componentclass RequestLogFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(RequestLogFilter.class);
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { long start = System.nanoTime(); log.info("-> {} {}", request.getMethod(), request.getRequestURI()); chain.doFilter(request, response); // pass the request on: next filter, then the controller long ms = (System.nanoTime() - start) / 1_000_000; log.info("<- {} {} answered {} in {} ms", request.getMethod(), request.getRequestURI(), response.getStatus(), ms); }}$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/1
401
$ curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass-1 http://localhost:8080/api/v1/products/1
200
Server log (the 401 request left no line at all):
... INFO 27300 --- [nio-8080-exec-3] c.shoplite.lab.common.RequestLogFilter : -> GET /api/v1/products/1
... INFO 27300 --- [nio-8080-exec-3] c.shoplite.lab.common.RequestLogFilter : <- GET /api/v1/products/1 answered 200 in 55 msWhat this code does
OncePerRequestFilteris Spring's base class for servlet filters;@Componentmakes Spring Boot register it with Tomcat. The lab project has two in-memory users,ashaandadmin, and a few products.- The request without credentials got 401 and never reached this filter: the security filter runs earlier (order -100) and answered by itself.
chain.doFilter(...)is the line that passes the request on; the code after it runs when the response comes back.
A filter gets the request, the response and the rest of the chain. It can look at the request, call chain.doFilter(...) to pass it on, run more code when the answer comes back, or answer by itself and never call the chain.
Why filters for security? A check in every controller method is easy to forget once, and one forgotten check is a hole. A filter sits in front of all controllers, so one rule covers every endpoint, including ones added next year.
Trace the code
Follow a request through two filters
Variables
- hasHeader
- false
Output
(nothing printed yet)Line 3The request carries no Authorization header.
DelegatingFilterProxy and FilterChainProxy
DelegatingFilterProxy is the one servlet filter that Spring Boot registers with Tomcat for security. It hands each request to the Spring bean named springSecurityFilterChain.
Tomcat calls one proxy, and the proxy leads to the security filters. The picture shows the whole path, and a real stack trace follows.
Example 3 · The proxy path in a real stack trace
Runs in: the shoplite-api Spring Boot project
# Part of the stack trace Spring Security logs at TRACE level for a rejected request.# Read it from the bottom up: Tomcat first, the security filters last.org.springframework.security.authorization.AuthorizationDeniedException: Access Denied at org.springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:99) ... at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:126) ... at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:198) ... at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:118) ... at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:237) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:195) ... at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$CompositeFilterChainProxy.doFilter(WebSecurityConfiguration.java:317) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:355) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:272) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:111) ... at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:199) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:111) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:165)Bottom to top: Tomcat ApplicationFilterChain -> CharacterEncodingFilter and other Boot filters -> DelegatingFilterProxy -> CompositeFilterChainProxy -> FilterChainProxy -> CsrfFilter ... BasicAuthenticationFilter ... ExceptionTranslationFilter -> AuthorizationFilter (throws Access Denied)
What this code does
DelegatingFilterProxy.doFilteris called by Tomcat like any servlet filter, then hands over to the Spring bean (CompositeFilterChainProxy, which wrapsFilterChainProxy).FilterChainProxy.doFilterInternalthen runs the security filters of the matching chain, one inside the other.- The exception is thrown in
AuthorizationFilterand caught byExceptionTranslationFilter, which sits just above it in the chain.
Tomcat knows nothing about Spring beans, so this proxy is the bridge. The bean leads to FilterChainProxy, which holds one or more SecurityFilterChain objects, each with a request matcher and a list of security filters. It picks the first chain whose matcher fits and runs only that chain's filters; shoplite-api has one chain that matches any request.
Read the stack trace from the bottom: Tomcat's ApplicationFilterChain, then DelegatingFilterProxy, then FilterChainProxy, then the security filters themselves.
@Component filter (like RequestLogFilter in Example 2) runs after the security chain by default, because the security filter has order -100 (spring.security.filter.order). That is why the rejected request never reached it.The important filters, in order
AuthorizationFilter is the last security filter. It checks the access rules and decides whether this caller may make this request.
Print the filters of the chain in the order they run, using the lab project.
Example 4 · src/main/java/com/shoplite/lab/security/FilterListPrinter.java
Runs in: the security-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.security;
import java.util.List;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;import org.springframework.security.web.SecurityFilterChain;
import jakarta.servlet.Filter;
/** Prints every security filter chain and its filters, in the order they run. */@Componentclass FilterListPrinter implements CommandLineRunner {
private final List<SecurityFilterChain> chains;
FilterListPrinter(List<SecurityFilterChain> chains) { this.chains = chains; }
@Override public void run(String... args) { System.out.println("Security filter chains: " + chains.size()); for (SecurityFilterChain chain : chains) { List<Filter> filters = chain.getFilters(); for (int i = 0; i < filters.size(); i++) { System.out.printf("%2d. %s%n", i + 1, filters.get(i).getClass().getSimpleName()); } } }}$ java -jar target/security-lab-0.0.1-SNAPSHOT.jar ... ... Started SecurityLabApplication in 5.617 seconds (process running for 6.854) Security filter chains: 1 1. DisableEncodeUrlFilter 2. WebAsyncManagerIntegrationFilter 3. SecurityContextHolderFilter 4. HeaderWriterFilter 5. CsrfFilter 6. LogoutFilter 7. UsernamePasswordAuthenticationFilter 8. DefaultResourcesFilter 9. DefaultLoginPageGeneratingFilter 10. DefaultLogoutPageGeneratingFilter 11. BasicAuthenticationFilter 12. RequestCacheAwareFilter 13. SecurityContextHolderAwareRequestFilter 14. AnonymousAuthenticationFilter 15. ExceptionTranslationFilter 16. AuthorizationFilter shoplite-api with logging.level.org.springframework.security=DEBUG prints its own list at startup: ... DEBUG ... o.s.s.web.DefaultSecurityFilterChain : Will secure any request with filters: DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CorsFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter, DefaultResourcesFilter, DefaultLoginPageGeneratingFilter, DefaultLogoutPageGeneratingFilter, BasicAuthenticationFilter, RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, ExceptionTranslationFilter, AuthorizationFilter
What this code does
- Spring gives the runner every
SecurityFilterChainbean;getFilters()returns the filters in the order they run. - The lab has no CORS configuration source, so it has 16 filters;
shoplite-apihasCorsFilteras number 5, for 17 in total. - Without the runner, the DEBUG line
Will secure any request with filters: ...at startup shows the same list.
The order is fixed by Spring Security, and it matters: a filter can only use what the filters before it found. With Boot's default setup, shoplite-api has 17. The ones to know:
SecurityContextHolderFilter: prepares an empty security context for this request and clears it at the end.CorsFilter: answers cross-origin browser checks (the CORS module). It appears when the app has a CORS configuration source; ShopLite gets one from Spring MVC.CsrfFilter: rejects state-changing requests (POST, PUT, PATCH, DELETE) without a CSRF token, with 403.BasicAuthenticationFilter(andUsernamePasswordAuthenticationFilterfor the login form): read credentials and sign the user in.
Then AnonymousAuthenticationFilter marks a request with no user as anonymousUser. ExceptionTranslationFilter catches security exceptions from later filters and turns them into 401 (start sign-in) or 403. The filters you never configured, such as the login page filters, come from Boot's default chain; your own configuration in the next lesson removes them.
Order of execution
Put the filters in running order
Which filter runs first, and which one last?
Following one request with TRACE logging
logging.level.org.springframework.security=TRACE makes Spring Security log every filter it calls and every decision it makes.
Switch on TRACE logging, send a guest GET and a signed-in POST, and read which filter stopped each request.
Example 5 · TRACE logs: a 401 and a surprising 401
Runs in: the shoplite-api Spring Boot project
# src/main/resources/application-dev.properties (only while you investigate)logging.level.org.springframework.security=TRACE# or, without editing any file:java -jar target/shoplite-api-1.0.0.jar --logging.level.org.springframework.security=TRACEcurl -i http://localhost:8080/api/v1/products/1curl -i -u user:3991867c-8fc7-4e5b-a5fc-ca2558e3ab5e -H "Content-Type: application/json" \ -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}' \ http://localhost:8080/api/v1/productsRequest 1: GET /api/v1/products/1 with no credentials -> 401 DEBUG ... o.s.security.web.FilterChainProxy : Securing GET /api/v1/products/1 TRACE ... o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/17) ... TRACE ... o.s.security.web.FilterChainProxy : Invoking CsrfFilter (6/17) TRACE ... o.s.security.web.csrf.CsrfFilter : Did not protect against CSRF since request did not match IsNotHttpMethod [TRACE, HEAD, GET, OPTIONS] ... TRACE ... o.s.security.web.FilterChainProxy : Invoking BasicAuthenticationFilter (12/17) TRACE ... o.s.s.w.a.www.BasicAuthenticationFilter : Did not process authentication request since failed to find username and password in Basic Authorization header ... TRACE ... o.s.security.web.FilterChainProxy : Invoking AnonymousAuthenticationFilter (15/17) TRACE ... o.s.security.web.FilterChainProxy : Invoking ExceptionTranslationFilter (16/17) TRACE ... o.s.security.web.FilterChainProxy : Invoking AuthorizationFilter (17/17) TRACE ... estMatcherDelegatingAuthorizationManager : Authorizing GET /api/v1/products/1 TRACE ... estMatcherDelegatingAuthorizationManager : Checking authorization on GET /api/v1/products/1 using org.springframework.security.authorization.AuthenticatedAuthorizationManager@5a295640 TRACE ... o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, ..., Granted Authorities=[ROLE_ANONYMOUS]] TRACE ... o.s.s.w.a.ExceptionTranslationFilter : Sending AnonymousAuthenticationToken [Principal=anonymousUser, ...] to authentication entry point since access is denied org.springframework.security.authorization.AuthorizationDeniedException: Access Denied ... DEBUG ... s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@2da585b1 DEBUG ... o.s.security.web.FilterChainProxy : Securing GET /error Request 2: POST /api/v1/products with the right password -> 401 (!) DEBUG ... o.s.security.web.FilterChainProxy : Securing POST /api/v1/products ... TRACE ... o.s.security.web.FilterChainProxy : Invoking CsrfFilter (6/17) TRACE ... o.s.s.web.csrf.CsrfTokenRequestHandler : Did not find a CSRF token in the [X-CSRF-TOKEN] request header TRACE ... o.s.s.web.csrf.CsrfTokenRequestHandler : Did not find a CSRF token in the [_csrf] request parameter DEBUG ... o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost:8080/api/v1/products DEBUG ... o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code DEBUG ... o.s.security.web.FilterChainProxy : Securing GET /error ... TRACE ... o.s.s.w.a.ExceptionTranslationFilter : Sending AnonymousAuthenticationToken [...] to authentication entry point since access is denied
What this code does
- Request 1:
AuthorizationFilterdeniesanonymousUserbecause the rule says "authenticated", and the Basic entry point answers 401. - Request 2:
CsrfFilterstops the POST with 403 beforeBasicAuthenticationFilter(filter 12) could read the password. - The 403 is forwarded to
/error, which is not public and has no credentials, so the client finally sees 401.
It is the fastest way to answer "why did I get 401 or 403?": find the request's Securing ... line, then follow it down to the filter that stopped it. For the GET with no credentials, BasicAuthenticationFilter finds no header, the anonymous filter marks the caller as anonymousUser, and AuthorizationFilter denies access, so the entry point sends 401. For the POST, the request never reaches BasicAuthenticationFilter: CsrfFilter (filter 6) finds no CSRF token and answers 403.
But the client saw 401, not 403. The 403 is sent as an error, and Tomcat forwards errors to /error. That second request (Securing GET /error) runs through the chain again, without credentials, and is denied with 401. The Permitting public endpoints lesson opens /error so real errors stay visible.
The authentication flow: AuthenticationManager, provider, Authentication
Authentication is the object that holds who is calling: the principal (the user), the credentials (the password) and the authorities (roles).
The picture shows the steps from a password to a signed-in user. The program below runs the same objects with no web server.
Example 6 · AuthenticationFlowDemo: the manager without a web server
Runs in: a Maven project with spring-security-core 7.1.1
package com.shoplite.lab;
import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.ProviderManager;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.authentication.dao.DaoAuthenticationProvider;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/** The authentication flow without any web server: the same objects BasicAuthenticationFilter uses. */public class AuthenticationFlowDemo {
public static void main(String[] args) { // Where users come from (the next module reads them from MySQL instead) UserDetailsService users = new InMemoryUserDetailsManager( User.withUsername("asha").password("{noop}asha-pass-1").roles("CUSTOMER").build());
// The provider that checks a username and password against those users DaoAuthenticationProvider provider = new DaoAuthenticationProvider(users); provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
// The manager: asks each provider in turn (here only one) AuthenticationManager manager = new ProviderManager(provider);
Authentication request = UsernamePasswordAuthenticationToken.unauthenticated("asha", "asha-pass-1"); System.out.println("Before: authenticated=" + request.isAuthenticated() + ", principal=" + request.getPrincipal());
Authentication result = manager.authenticate(request); System.out.println("After: authenticated=" + result.isAuthenticated() + ", name=" + result.getName() + ", credentials=" + result.getCredentials() + ", authorities=" + result.getAuthorities().stream().map(a -> a.getAuthority()).sorted().toList());
tryLogin(manager, "asha", "wrong-pass"); tryLogin(manager, "ravi", "asha-pass-1"); }
private static void tryLogin(AuthenticationManager manager, String username, String password) { try { manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, password)); System.out.println(username + ": signed in"); } catch (AuthenticationException e) { System.out.println(username + "/" + password + " -> " + e.getClass().getSimpleName() + ": " + e.getMessage()); } }}Before: authenticated=false, principal=asha After: authenticated=true, name=asha, credentials=null, authorities=[FACTOR_PASSWORD, ROLE_CUSTOMER] asha/wrong-pass -> BadCredentialsException: Bad credentials ravi/asha-pass-1 -> BadCredentialsException: Bad credentials
What this code does
unauthenticated(...)builds the request object;manager.authenticate(...)returns a new, authenticated object or throws anAuthenticationException.- After success the credentials are
null:ProviderManagererases the password so it does not stay in memory longer than needed. {noop}means the stored password is plain text (lab only). The next module stores BCrypt hashes and uses the same flow.
Before sign-in an Authentication is an unchecked request (isAuthenticated() is false); after a successful check it is a new, trusted object. The AuthenticationManager is the one entry point that checks credentials. Its usual implementation, ProviderManager, asks a list of AuthenticationProvider objects in turn. For a username and password that is DaoAuthenticationProvider: it loads the user through a UserDetailsService and compares the password with a PasswordEncoder. BasicAuthenticationFilter only builds the request object from the header and calls the manager.
Notice the two failures in the output: a wrong password and an unknown user give the same Bad credentials message, so an attacker cannot learn which usernames exist. Also notice FACTOR_PASSWORD: Spring Security 7 adds this authority to record how the user signed in.
Next step
Check your understanding
12 quick questions