The security filter chain

Spring Security · lesson 1 of 31 · 3 min read

Know how Spring Security hooks into a servlet app and what happens before your controller runs.

Open this lesson in the learning hub

Key points

  • Spring Security is one servlet filter. Boot registers it as springSecurityFilterChain and every request goes through it.
  • That filter delegates to a chain of a dozen-plus small filters. Each has one job: restore the context, check CSRF, log in, authorize.
  • Order is fixed and it matters. CsrfFilter runs early; AuthorizationFilter runs last, right before your controller.
  • Nothing reaches a controller until the chain says yes. A rejected request never touches your code.
  • Add your own filter with addFilterBefore. Anchor it to a known filter instead of guessing a position.

Example

public class RequestIdFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        MDC.put("requestId", UUID.randomUUID().toString());
        try {
            chain.doFilter(req, res);   // hand off to the next filter
        } finally {
            MDC.remove("requestId");
        }
    }
}

@Bean
SecurityFilterChain app(HttpSecurity http) throws Exception {
    return http
        .addFilterBefore(new RequestIdFilter(), UsernamePasswordAuthenticationFilter.class)
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .build();
}

Spring Security is a chain of small filters — learn the order and the rest makes sense.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.