DEV Community

Dev Cookies
Dev Cookies

Posted on

πŸ” Spring Security Request Lifecycle in Spring Boot – A Deep Dive

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

  1. Why Spring Security?
  2. High-Level Flow
  3. Security Filter Chain Explained
  4. Authentication Lifecycle
  5. Authorization Lifecycle
  6. Key Components
  7. Integration with Spring MVC
  8. Flow Diagram
  9. 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
Enter fullscreen mode Exit fullscreen mode

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:

  1. Filter Intercepts Request
    E.g., UsernamePasswordAuthenticationFilter intercepts a /login POST request.

  2. Extracts Credentials
    Username/password are extracted and passed as a token.

  3. Delegates to AuthenticationManager
    Typically uses ProviderManager.

  4. Calls AuthenticationProvider
    Like DaoAuthenticationProvider, which calls UserDetailsService.

  5. Validates User

  • Loads user from DB
  • Validates password using PasswordEncoder
  1. Creates Authentication Object
    Upon success, an Authentication object is created and stored in the SecurityContext.

  2. SecurityContext Stored
    The SecurityContextPersistenceFilter stores the authenticated user in the session or SecurityContextHolder.


πŸ›‘οΈ Authorization Lifecycle

Authorization determines what an authenticated user is allowed to do.

πŸ” Steps:

  1. Request Reaches FilterSecurityInterceptor
  2. Determines Required Authorities (via annotations or config)
  • @PreAuthorize("hasRole('ADMIN')")
    1. Fetches Current User’s Authorities
    2. Compares Access
    3. 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]
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 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();
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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();
Enter fullscreen mode Exit fullscreen mode

🧠 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)