Video in progress

Middle 🌱 Spring

What is the filter chain in Spring Security, and how is a request checked?

Spring Security is a chain of Servlet filters. Before a request reaches the controller it passes through the filters: first authentication (who are you?), then authorization (are you allowed?). Who the user is lives in the SecurityContext.

📖 Answer

A single filter is registered with the Servlet container — DelegatingFilterProxy, which hands off to FilterChainProxy. Inside it, the SecurityFilterChain matching the URL is chosen and its filters run in order, for example:

  • CsrfFilter
  • UsernamePasswordAuthenticationFilter (form login) or BearerTokenAuthenticationFilter (JWT)
  • ExceptionTranslationFilter — turns errors into 401/403
  • AuthorizationFilter — the final check

Modern setup (Spring Security 6):

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/api/**")
        .authorizeHttpRequests(a -> a
            .requestMatchers("/api/public/**").permitAll()
            .requestMatchers("/api/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
        .build();
}

After login the user sits in SecurityContextHolder.getContext().getAuthentication() — in a controller you get it with @AuthenticationPrincipal.

If you're stuck on "why 403?", set logging.level.org.springframework.security=TRACE — the log shows what every filter did.