11.1 Security Architecture and Filter Chain Overview
Spring Security is a powerful framework responsible for Authentication and Authorization in Spring-based applications. Its core operation is based on a Servlet Filter chain.
1. Authentication vs Authorization
These are the two fundamental concepts of security.
- Authentication:"Who are you?" (Checking identity, e.g., Login)
- Authorization:"Do you have permission to access this resource?" (Access control)
2. Security Filter Chain
Spring Security uses multiple filters connected like a chain to intercept and process requests.
- FilterChainProxy: The core entry point of Spring Security, selecting the appropriate
SecurityFilterChainfor a request. - SecurityFilterChain: A list of filters applied to requests matching specific URI patterns.
Key Default Filters
- SecurityContextPersistenceFilter: Loads or stores the
SecurityContextfrom/to theSecurityContextRepository. - UsernamePasswordAuthenticationFilter: Handles form-based login using username and password.
- ExceptionTranslationFilter: Handles security exceptions (
AuthenticationException,AccessDeniedException) and generates appropriate responses. - FilterSecurityInterceptor: Determines the final authorization for the request.
3. Security Configuration (SecurityConfig)
In modern Spring Boot (3.x and above), component-based configuration using beans is recommended.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // Disable CSRF for API servers
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll() // Publicly accessible
.anyRequest().authenticated() // All other requests require authentication
)
.formLogin(Customizer.withDefaults()); // Enable default form login
return http.build();
}
}
🎯 Key Points
- Spring Security operates via a Filter Chain.
- Authentication is about identity, Authorization is about permissions.
- Security policies can be customized by configuring the
SecurityFilterChainbean.