Spring Security is a robust and highly customizable authentication and access-control framework. While Spring Boot makes its integration seamless, understanding the internal request lifecycle of Spring Security is essential for building secure, scalable, and maintainable systems.
In this blog, weβll explore how Spring Security fits into the Spring Boot request flow, breaking down its filters, authentication mechanisms, and authorization process β all the way from the incoming request to the final response.
π Table of Contents
- Why Spring Security?
- High-Level Flow
- Security Filter Chain Explained
- Authentication Lifecycle
- Authorization Lifecycle
- Key Components
- Integration with Spring MVC
- Flow Diagram
- Conclusion
π¨ Why Spring Security?
Spring Security protects applications from common security threats such as:
- Unauthorized access
- CSRF attacks
- Session hijacking
- Injection attacks
- Clickjacking
It offers comprehensive support for:
- Authentication (form, JWT, OAuth2, SSO)
- Authorization (role/permission-based)
- Password hashing, CORS, CSRF, and more
π High-Level Flow
When a request comes in, Spring Security intercepts it before it even hits your controller.
Client
β
Embedded Server
β
Spring Security Filter Chain
β
DispatcherServlet β Controller β Service β DB
β
Response
The Security Filter Chain acts like a wall between the incoming request and your application logic.
π§± Security Filter Chain Explained
Spring Security is built on the Servlet Filter API. When Spring Boot starts, it auto-registers a filter named springSecurityFilterChain.
This chain consists of multiple filters, applied in a specific order.
π Common Filters (Simplified Order)
| Filter | Purpose |
|---|---|
SecurityContextPersistenceFilter |
Load and save the SecurityContext
|
UsernamePasswordAuthenticationFilter |
Authenticates username/password |
BearerTokenAuthenticationFilter |
Parses and validates JWT tokens |
BasicAuthenticationFilter |
Handles HTTP Basic auth |
ExceptionTranslationFilter |
Handles auth/authorization exceptions |
FilterSecurityInterceptor |
Enforces authorization checks |
CsrfFilter |
Protects against CSRF attacks |
π‘ You can inspect the actual filter chain by enabling debug logs:
logging.level.org.springframework.security=DEBUG
π Authentication Lifecycle
Authentication is the process of verifying who the user is.
π Steps:
Filter Intercepts Request
E.g.,UsernamePasswordAuthenticationFilterintercepts a/loginPOST request.Extracts Credentials
Username/password are extracted and passed as a token.Delegates to
AuthenticationManager
Typically usesProviderManager.Calls
AuthenticationProvider
LikeDaoAuthenticationProvider, which callsUserDetailsService.Validates User
- Loads user from DB
- Validates password using
PasswordEncoder
Creates
AuthenticationObject
Upon success, anAuthenticationobject is created and stored in theSecurityContext.SecurityContext Stored
TheSecurityContextPersistenceFilterstores the authenticated user in the session or SecurityContextHolder.
π‘οΈ Authorization Lifecycle
Authorization determines what an authenticated user is allowed to do.
π Steps:
- Request Reaches
FilterSecurityInterceptor - Determines Required Authorities (via annotations or config)
-
@PreAuthorize("hasRole('ADMIN')")- Fetches Current Userβs Authorities
- Compares Access
- Allows or Denies Request
π§© Key Components
| Component | Purpose |
|---|---|
AuthenticationManager |
Delegates authentication |
UserDetailsService |
Loads user data from DB |
PasswordEncoder |
Hashes and verifies passwords |
SecurityContextHolder |
Stores user details per thread/request |
AccessDecisionManager |
Makes authorization decisions |
GrantedAuthority |
Represents a userβs role/permission |
Authentication |
Holds user credentials, authorities |
π Integration with Spring MVC
After authentication and authorization succeed:
- The request continues down the filter chain.
- It reaches the
DispatcherServlet. -
Normal Spring MVC flow resumes:
- HandlerMapping
- Controller
- Service
- Repository
- Response
π Flow Diagram
+------------+ +------------------+ +----------------------------+
| Client +-----> | Embedded Server +-----> | Spring Security Filters |
+------------+ +------------------+ +--------+-------------------+
β
[Authentication: is user valid?]
β
[Authorization: is user allowed?]
β
+-------------------------+
| DispatcherServlet |
+-------------------------+
β
+-------------------------+
| Controller β Service |
| β Repository β DB |
+-------------------------+
β
[Send Response]
π§ͺ Sample Configuration (Java Config)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
return username -> new User(username, passwordEncoder().encode("pass123"),
List.of(new SimpleGrantedAuthority("ROLE_USER")));
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
β
Bonus: Role of SecurityContextHolder
- Stores the currently authenticated user.
- Thread-local storage.
- Accessible anywhere in the app:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
π§ Conclusion
Spring Security provides powerful tools to secure your Spring Boot applications, but understanding its request lifecycle β especially the role of the filter chain, authentication manager, and security context β is key to mastering it.
Now that youβve walked through the full journey, you can:
- Customize login flows
- Implement JWT or OAuth2
- Build granular authorization rules
- Debug security issues with confidence
Top comments (0)