Open In App

Spring Security Architecture

Last Updated : 12 Sep, 2025
Comments
Improve
Suggest changes
5 Likes
Like
Report

Spring Security is a framework that provides authentication, authorization and protection against common attacks in Java applications. It is the de facto standard for securing Spring-based applications, offering flexible integration with modern security mechanisms such as JWT, OAuth2, LDAP and database-backed authentication.

architecture
Spring-Security

Core Components of Spring Security Architecture

1. Security Filter Chain

  • Acts as the entry point for all incoming requests.
  • Every incoming request passes through a chain of filters (e.g., UsernamePasswordAuthenticationFilter, BasicAuthenticationFilter).
  • Filters handle authentication, authorization, CSRF protection and session management.
  • Ensures modular and customizable security logic.

Example:

Java
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable()) // Disable CSRF for APIs
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .httpBasic(); // Basic Authentication
        return http.build();
    }
}

2. Authentication Manager

  • The core component responsible for user authentication.
  • Delegates authentication requests to one or more Authentication Providers.
  • Implements the Strategy pattern, meaning multiple authentication mechanisms (DB, LDAP, JWT, OAuth2) can work together.

Example:

Java
@Configuration
public class AuthManagerConfig {

    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }
}

3. Authentication Providers

Authentication Providers are the actual components that validate user credentials.

Examples:

  • DaoAuthenticationProvider: Uses database via UserDetailsService + PasswordEncoder.
  • JwtAuthenticationProvider: Validates JWT tokens.

Example:

Java
@Configuration
public class ProviderConfig {

    @Bean
    public DaoAuthenticationProvider authenticationProvider(
            UserDetailsService userDetailsService,
            PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        return provider;
    }
}

4. UserDetailsService

  • Loads user-specific data (username, password, roles) from a data source like a database.
  • Returns a UserDetails object.
  • Used primarily by providers like DaoAuthenticationProvider.

Example:

Java
@Configuration
public class UserConfig {

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            User.withUsername("john")
                .password(encoder.encode("password"))
                .roles("USER")
                .build(),
            User.withUsername("admin")
                .password(encoder.encode("admin123"))
                .roles("ADMIN")
                .build()
        );
    }
}

5. Password Encoder

  • Ensures secure password storage and validation.
  • Encodes raw passwords into secure hashes before saving/validation.

Example:

Java
@Configuration
public class PasswordConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // Strong hashing
    }
}

6. SecurityContextHolder

Stores the SecurityContext for the current request/thread. And holds the Authentication object, which contains:

  • Principal: Represents the logged-in user (username or user object).
  • Authorities: Roles/permissions granted to the user.

Example:

Java
@RestController
public class UserController {

    @GetMapping("/me")
    public String getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return "Logged in as: " + authentication.getName() +
               " | Roles: " + authentication.getAuthorities();
    }
}

How It Works Internally

  1. A client sends an HTTP Request.
  2. The request passes through the Security Filter Chain.
  3. The Authentication Manager delegates authentication to an appropriate Authentication Provider.
  4. The provider may use UserDetailsService and PasswordEncoder to validate credentials.
  5. Upon success, user details are stored in SecurityContextHolder.
  6. Authorization checks use the stored principal and authorities to allow or deny access.
  7. The processed request finally reaches the application’s controller and returns an HTTP Response.

Explore