Spring Security integrates with Spring MVC as a chain of servlet filters that sit in front of DispatcherServlet, intercepting every request to enforce authentication and authorization before it ever reaches a controller.
Key Points: • @EnableWebSecurity activates Spring Security's configuration support within the application context. • Modern configuration defines a SecurityFilterChain bean rather than extending WebSecurityConfigurerAdapter, which is deprecated. • The filter chain handles login, logout, CSRF protection, and session management centrally, before requests reach any controller. • URL-level authorization rules (authorizeHttpRequests) declare which paths require authentication or specific roles. • Because it runs as filters, Spring Security works with the same request regardless of whether the eventual handler is a traditional @Controller or a @RestController.
Example: A request to /admin/dashboard passes through the security filter chain first; if the user isn't authenticated they're redirected to a login page before DispatcherServlet, let alone the admin controller, ever sees the request.
Code Example:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
}Interview Tip: A concise interview answer is:
"Spring Security plugs in as a filter chain in front of DispatcherServlet, so it can authenticate and authorize requests before they ever reach a controller. I enable it with @EnableWebSecurity and define a SecurityFilterChain bean that declares which URL patterns need authentication or specific roles."