Filter chains in Spring Security
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every ShopLite request must be logged, checked for a token and checked for the right role. Doing that inside each controller would be messy; a line of filters does it once for all requests.
Servlet filters as Chain of Responsibility
Chain of Responsibility is a pattern where a request passes along a line of handlers; each handler can deal with it, pass it to the next handler, or stop it.
A servlet filter sees every HTTP request before the controller and the response after it. It does its work, then calls chain.doFilter(request, response) to hand over to the next filter.
public class RequestLogFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { System.out.println("-> " + request.getMethod() + " " + request.getRequestURI()); chain.doFilter(request, response); // pass the request on System.out.println("<- " + response.getStatus()); // on the way back }}Example 1 · A filter chain in plain Java
import java.util.List;
record Request(String method, String path) { }
class Response { int status = 200; String body = "";}
interface Filter { void doFilter(Request req, Response res, FilterChain chain);}
class FilterChain { private final List<Filter> filters; private final Runnable controller; private int next = 0;
FilterChain(List<Filter> filters, Runnable controller) { this.filters = filters; this.controller = controller; }
void doFilter(Request req, Response res) { if (next < filters.size()) { filters.get(next++).doFilter(req, res, this); // hand over to the next filter } else { controller.run(); // end of the chain } }}
class LoggingFilter implements Filter { public void doFilter(Request req, Response res, FilterChain chain) { System.out.println("-> " + req.method() + " " + req.path()); chain.doFilter(req, res); System.out.println("<- " + res.status); // runs on the way back }}
class GzipFilter implements Filter { public void doFilter(Request req, Response res, FilterChain chain) { System.out.println(" gzip: before"); chain.doFilter(req, res); System.out.println(" gzip: compress " + res.body.length() + " chars"); }}
public class FilterChainBasicsDemo { public static void main(String[] args) { Request req = new Request("GET", "/api/v1/products"); Response res = new Response(); FilterChain chain = new FilterChain(List.of(new LoggingFilter(), new GzipFilter()), () -> { System.out.println(" controller: list products"); res.body = "[{\"id\":7,\"name\":\"Earbuds\"}]"; }); chain.doFilter(req, res); }}-> GET /api/v1/products
gzip: before
controller: list products
gzip: compress 27 chars
<- 200What this code does
FilterChainkeeps an index of the next filter. Each filter callschain.doFilterto hand over, and the controller runs at the end.- The output nests: logging starts first and finishes last, because its "after" code waits for everything inside it to return.
The last link is the servlet that runs your controller. Each filter knows only "the next one", and the order of the list decides the order of work. Code before chain.doFilter runs on the way in and code after it on the way back out, so filters nest like brackets.
Order of execution
Order the printed lines
Tap the steps in the order they happen for one request.
OncePerRequestFilter is Spring's base class for filters. It makes sure the filter runs only once per request, even when the request is forwarded inside the server.SecurityFilterChain and the order of its filters
A SecurityFilterChain is an ordered list of Spring Security filters that applies to the requests matching it. Spring Security runs it inside one servlet filter, FilterChainProxy.
Spring Security adds one servlet filter, FilterChainProxy, to the server. Inside it, a SecurityFilterChain holds the ordered security filters, and each line of your HttpSecurity configuration switches some of them on.
@BeanSecurityFilterChain api(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll() .requestMatchers("/api/v1/admin/**").hasRole("ADMIN") .anyRequest().authenticated()) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())); return http.build();}A simplified order for ShopLite's stateless JWT API, first to last (@EnableWebSecurity(debug = true) prints the real list for every request):
SecurityContextHolderFilter,HeaderWriterFilter,CorsFilter: set up the request context, security headers and CORS.BearerTokenAuthenticationFilter: readsAuthorization: Bearer ...and, if the token is valid, stores the user in the security context.AnonymousAuthenticationFilter: marks a request with no user as anonymous.ExceptionTranslationFilter, thenAuthorizationFilterlast: check the rules and turn failures into 401 or 403.
How a request is stopped or passed on
401 Unauthorized means the caller is not signed in. 403 Forbidden means the caller is signed in but is not allowed to do this.
A filter passes the request on by calling chain.doFilter. It stops the request by writing a response, such as status 401, and returning without calling it.
Example 2 · Stopping the chain or passing it on
import java.util.List;import java.util.Map;
record Request(String path, Map<String, String> headers) { }
class Response { int status = 200;}
interface Filter { void doFilter(Request req, Response res, FilterChain chain);}
class FilterChain { private final List<Filter> filters; private final Runnable controller; private int next = 0;
FilterChain(List<Filter> filters, Runnable controller) { this.filters = filters; this.controller = controller; }
void doFilter(Request req, Response res) { if (next < filters.size()) { filters.get(next++).doFilter(req, res, this); } else { controller.run(); } }}
class BearerTokenFilter implements Filter { public void doFilter(Request req, Response res, FilterChain chain) { String auth = req.headers().get("Authorization"); if (auth == null || !auth.startsWith("Bearer ")) { res.status = 401; // stop: answer now System.out.println(" token filter: no token, 401, chain stops"); return; // chain.doFilter is NOT called } System.out.println(" token filter: token found, passing on"); chain.doFilter(req, res); // pass on }}
public class StopOrPassDemo { static void handle(Request req) { Response res = new Response(); new FilterChain(List.of(new BearerTokenFilter()), () -> System.out.println(" controller: show orders")).doFilter(req, res); System.out.println(" status " + res.status); }
public static void main(String[] args) { System.out.println("GET /api/v1/me/orders without a token:"); handle(new Request("/api/v1/me/orders", Map.of())); System.out.println("GET /api/v1/me/orders with a token:"); handle(new Request("/api/v1/me/orders", Map.of("Authorization", "Bearer t-riya"))); }}GET /api/v1/me/orders without a token: token filter: no token, 401, chain stops status 401 GET /api/v1/me/orders with a token: token filter: token found, passing on controller: show orders status 200
What this code does
- Without a token, the filter sets 401 and returns without calling
chain.doFilter, so the controller never runs. - With a token, the filter passes the request on and the controller answers with 200.
Spring Security's authorization step stops requests a little differently: AuthorizationFilter throws an AccessDeniedException, and ExceptionTranslationFilter, placed just before it, catches it and picks 401 or 403. The filters after a stopping filter, and the controller, never run.
Predict the output
Which status comes back?
Walk the filters and pick the status.
Round 1 of 3
A guest sends the request. What status?
Simulating a security filter chain in plain Java
A plain Java model needs a Filter interface, a FilterChain that remembers the next filter, and four filters that copy Spring's roles. Five ShopLite requests then show every path.
Example 3 · A small model of Spring Security's chain
import java.util.List;import java.util.Map;import java.util.Set;
record Request(String method, String path, String token) { }
class Response { int status = 200; String body = "";}
record User(String name, Set<String> roles) { }
class AccessDeniedException extends RuntimeException { AccessDeniedException(String message) { super(message); }}
class SecurityContext { User user;}
interface Filter { void doFilter(Request req, Response res, SecurityContext ctx, FilterChain chain);}
class FilterChain { private final List<Filter> filters; private final Runnable controller; private int next = 0;
FilterChain(List<Filter> filters, Runnable controller) { this.filters = filters; this.controller = controller; }
void doFilter(Request req, Response res, SecurityContext ctx) { if (next < filters.size()) { filters.get(next++).doFilter(req, res, ctx, this); } else { controller.run(); } }}
class LoggingFilter implements Filter { public void doFilter(Request req, Response res, SecurityContext ctx, FilterChain chain) { chain.doFilter(req, res, ctx); System.out.println(req.method() + " " + req.path() + " -> " + res.status + " " + res.body); }}
// Like ExceptionTranslationFilter: turns AccessDeniedException into 401 or 403class ExceptionTranslationFilter implements Filter { public void doFilter(Request req, Response res, SecurityContext ctx, FilterChain chain) { try { chain.doFilter(req, res, ctx); } catch (AccessDeniedException e) { res.status = ctx.user == null ? 401 : 403; res.body = ctx.user == null ? "unauthorized" : "forbidden"; } }}
// Like BearerTokenAuthenticationFilter: a valid token fills the security contextclass TokenAuthFilter implements Filter { private final Map<String, User> tokens;
TokenAuthFilter(Map<String, User> tokens) { this.tokens = tokens; }
public void doFilter(Request req, Response res, SecurityContext ctx, FilterChain chain) { if (req.token() != null) { ctx.user = tokens.get(req.token()); } chain.doFilter(req, res, ctx); }}
// Like AuthorizationFilter: checks the rules, last in the chainclass AuthorizationFilter implements Filter { public void doFilter(Request req, Response res, SecurityContext ctx, FilterChain chain) { boolean publicRead = req.method().equals("GET") && req.path().startsWith("/api/v1/products"); if (!publicRead) { if (ctx.user == null) { throw new AccessDeniedException("not signed in"); } if (req.path().startsWith("/api/v1/admin") && !ctx.user.roles().contains("ADMIN")) { throw new AccessDeniedException("needs ADMIN"); } } chain.doFilter(req, res, ctx); }}
public class SecurityChainSimDemo { public static void main(String[] args) { Map<String, User> tokens = Map.of( "t-riya", new User("riya", Set.of("CUSTOMER")), "t-admin", new User("anil", Set.of("CUSTOMER", "ADMIN")));
List<Request> requests = List.of( new Request("GET", "/api/v1/products", null), new Request("GET", "/api/v1/me/orders", null), new Request("GET", "/api/v1/me/orders", "t-riya"), new Request("POST", "/api/v1/admin/products", "t-riya"), new Request("POST", "/api/v1/admin/products", "t-admin"));
for (Request req : requests) { Response res = new Response(); SecurityContext ctx = new SecurityContext(); List<Filter> filters = List.of(new LoggingFilter(), new ExceptionTranslationFilter(), new TokenAuthFilter(tokens), new AuthorizationFilter()); new FilterChain(filters, () -> res.body = "handled for " + (ctx.user == null ? "guest" : ctx.user.name())) .doFilter(req, res, ctx); } }}GET /api/v1/products -> 200 handled for guest GET /api/v1/me/orders -> 401 unauthorized GET /api/v1/me/orders -> 200 handled for riya POST /api/v1/admin/products -> 403 forbidden POST /api/v1/admin/products -> 200 handled for anil
What this code does
TokenAuthFilterfills the context from the token;AuthorizationFilterthrowsAccessDeniedExceptionwhen a rule fails.ExceptionTranslationFiltersits before it and turns the exception into 401 for a guest and 403 for a signed-in customer on an admin URL, as Spring does.
The four filters: a logging filter, an exception translation filter, a token filter that fills a security context, and an authorization filter that throws when a rule fails.
The five requests are a public product list, a guest asking for orders, a signed-in customer, a customer on an admin URL, and an admin.
Find the bug
Find the bug in the chain
Click the line that breaks the chain.
Signed-in customers get 401. Which line is wrong?
Round 1 of 2Where a custom filter fits in the chain
http.addFilterBefore(filter, SomeFilter.class), addFilterAfter and addFilterAt put your own filter at a chosen place in a SecurityFilterChain. The place matters.
http.addFilterBefore(new RateLimitFilter(), BearerTokenAuthenticationFilter.class);http.addFilterAfter(new AuditFilter(), BearerTokenAuthenticationFilter.class);Example 4 · Placing a custom filter before another
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
record Request(String ip, String path) { }
class Response { int status = 200;}
interface Filter { void doFilter(Request req, Response res, FilterChain chain);}
class FilterChain { private final List<Filter> filters; private final Runnable controller; private int next = 0;
FilterChain(List<Filter> filters, Runnable controller) { this.filters = filters; this.controller = controller; }
void doFilter(Request req, Response res) { if (next < filters.size()) { filters.get(next++).doFilter(req, res, this); } else { controller.run(); } }}
class TokenCheckFilter implements Filter { public void doFilter(Request req, Response res, FilterChain chain) { System.out.println(" token check (costly) for " + req.ip()); chain.doFilter(req, res); }}
class RateLimitFilter implements Filter { private final Map<String, Integer> hits = new HashMap<>(); private final int limit;
RateLimitFilter(int limit) { this.limit = limit; }
public void doFilter(Request req, Response res, FilterChain chain) { int count = hits.merge(req.ip(), 1, Integer::sum); if (count > limit) { res.status = 429; // Too Many Requests return; } chain.doFilter(req, res); }}
// Like http.addFilterBefore(custom, SomeFilter.class)class ChainBuilder { private final List<Filter> filters = new ArrayList<>();
ChainBuilder add(Filter f) { filters.add(f); return this; }
ChainBuilder addBefore(Filter f, Class<? extends Filter> existing) { for (int i = 0; i < filters.size(); i++) { if (existing.isInstance(filters.get(i))) { filters.add(i, f); return this; } } throw new IllegalArgumentException("No filter of type " + existing.getSimpleName()); }
List<Filter> build() { return List.copyOf(filters); }}
public class CustomFilterPositionDemo { public static void main(String[] args) { List<Filter> filters = new ChainBuilder() .add(new TokenCheckFilter()) .addBefore(new RateLimitFilter(2), TokenCheckFilter.class) .build();
for (int i = 1; i <= 3; i++) { Request req = new Request("10.0.0.5", "/api/v1/products"); Response res = new Response(); new FilterChain(filters, () -> System.out.println(" controller")).doFilter(req, res); System.out.println("Request " + i + ": " + res.status); } }}token check (costly) for 10.0.0.5 controller Request 1: 200 token check (costly) for 10.0.0.5 controller Request 2: 200 Request 3: 429
What this code does
addBeforeinserts the rate limiter in front of the costly token check, likehttp.addFilterBefore.- The third request from the same address gets 429 and never reaches the token check or the controller.
Put a rate limiter before the token check, so a flood of bad requests is stopped cheaply; put a filter that needs the signed-in user after authentication.
A common trap: if your filter is also a @Component, Spring Boot registers it a second time as a normal servlet filter outside security. Either do not make it a bean, or switch off the extra registration with a FilterRegistrationBean whose setEnabled(false) is called.
Predict the output
Where does the limiter go?
Pick what this placement does.
A bot sends many requests with bad tokens. What does this placement do?
Next step
Check your understanding
12 quick questions