How Spring Security Works: The Filter Chain
Spring Security protects your app with a chain of servlet filters that authenticate the request and then check authorization. Interviewers ask how a request flows through it, what the SecurityContext is, and how to configure it in Spring Boot 3 and 4.
What you will learn
- Explain DelegatingFilterProxy, FilterChainProxy and SecurityFilterChain
- Follow authentication through AuthenticationManager and providers
- Configure authorization rules with a SecurityFilterChain bean
- Use method security with @PreAuthorize
Key concepts
Filter chain
A servlet filter (DelegatingFilterProxy) hands each request to FilterChainProxy, which picks the matching SecurityFilterChain and runs its filters: CORS, CSRF, authentication filters, exception translation and authorization.
Authentication
An authentication filter builds an Authentication token; the AuthenticationManager delegates to AuthenticationProviders (such as DaoAuthenticationProvider with a UserDetailsService and PasswordEncoder). On success the result goes into the SecurityContext.
SecurityContextHolder
Holds the current Authentication, by default in a ThreadLocal for the request thread. Read it with @AuthenticationPrincipal in controllers.
Authorization
URL rules in authorizeHttpRequests and method rules with @PreAuthorize("hasRole('ADMIN') or #id == authentication.name") after @EnableMethodSecurity.
Step by step
Modern configuration (no WebSecurityConfigurerAdapter)
@Configuration
@EnableMethodSecurity
class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // stateless API with bearer tokens
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health", "/api/auth/**").permitAll()
.requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
@Bean
PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }
}Examples
Method security with ownership
@PreAuthorize("hasRole('ADMIN') or @orderSecurity.isOwner(#orderId, authentication)")
@GetMapping("/api/orders/{orderId}")
OrderResponse get(@PathVariable Long orderId) { ... }Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Print the filters in your SecurityFilterChain at startup and explain what each does.
- Explain hasRole("ADMIN") vs hasAuthority("ROLE_ADMIN").
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
When is it safe to disable CSRF?
When the API is stateless and authenticated with a token in the Authorization header, because browsers do not attach that header automatically. If you authenticate with session cookies, keep CSRF protection on.
401 vs 403 in Spring Security?
AuthenticationEntryPoint handles unauthenticated requests (401). AccessDeniedHandler handles authenticated users without permission (403). ExceptionTranslationFilter decides which one to call.
Summary
Requests pass through the SecurityFilterChain: authentication fills the SecurityContext, then URL and method rules authorize. Configure with a SecurityFilterChain bean, a delegating PasswordEncoder and @PreAuthorize for fine-grained checks.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus