Back to Spring Security
    Module 1.2

    Internal Architecture

    Understanding the filter chain, core components, and authentication flow inside Spring Security.

    The Security Filter Chain

    In a Spring Boot application, SecurityFilterAutoConfiguration automatically registers the DelegatingFilterProxy filter with the name springSecurityFilterChain. Once a request reaches DelegatingFilterProxy, Spring delegates the processing to FilterChainProxy bean that utilizes the SecurityFilterChain to execute all filters for the current request.

    Request Flow Through Spring Security:
    ═══════════════════════════════════════════════════════════════════
    HTTP Request
    │
    ▼
    ┌─────────────────────────────────┐
    │    DelegatingFilterProxy        │  ← Registered automatically
    │    (springSecurityFilterChain)  │     as a servlet filter
    └────────────────┬────────────────┘
    │
    ▼
    ┌─────────────────────────────────┐
    │       FilterChainProxy          │  ← Manages SecurityFilterChains
    └────────────────┬────────────────┘
    │
    ▼
    ┌─────────────────────────────────┐
    │      SecurityFilterChain        │  ← Chain of security filters
    │                                 │
    │  ┌───────────────────────────┐  │
    │  │ SecurityContextPersistence│  │  Manages security context
    │  │ CsrfFilter                │  │  CSRF protection
    │  │ LogoutFilter              │  │  Handles logout
    │  │ UsernamePasswordAuth...   │  │  Form login
    │  │ BasicAuthenticationFilter │  │  HTTP Basic auth
    │  │ RequestCacheAware...      │  │  Caches requests
    │  │ SecurityContextHolder...  │  │  Stores context
    │  │ AnonymousAuth...          │  │  Anonymous users
    │  │ SessionManagement...      │  │  Session security
    │  │ ExceptionTranslation...   │  │  Exception handling
    │  │ AuthorizationFilter       │  │  Access decisions
    │  └───────────────────────────┘  │
    └────────────────┬────────────────┘
    │
    ▼
    Your Controller
    ═══════════════════════════════════════════════════════════════════
    DelegatingFilterProxy

    The bridge between the servlet container and Spring's application context. It intercepts incoming HTTP requests and delegates processing to the FilterChainProxy.

    SecurityFilterChain

    Contains the ordered list of security filters. Each filter handles a specific security aspect like authentication, CSRF protection, or authorization.

    The Mall Analogy

    Imagine your Spring Boot application is like a shopping mall. The mall has various sections—stores, a food court, and a VIP lounge. Some areas are open to everyone, while others (like the VIP lounge) require special access.

    • DelegatingFilterProxy is the main security gate at the mall entrance
    • The gate ensures every visitor is routed through appropriate security checkpoints (filters) managed by FilterChainProxy
    • Each checkpoint in the SecurityFilterChain ensures only authorized visitors access restricted areas
    • If you clear all necessary checkpoints, you can freely explore the mall, including restricted VIP areas

    Core Spring Security Components

    Core Spring Security components are used throughout a Spring Boot application to manage authentication, authorization, and overall security. Understanding these components is essential for customizing security behavior.

    UserDetails

    The UserDetails interface represents a user in Spring Security. It provides methods to get user information such as username, password, and authorities (roles/permissions).

    Purpose: Encapsulate user information for authentication and authorization. Implementation: Extend your User Entity to implement this interface.

    UserDetailsService

    The UserDetailsService interface is a core component used to retrieve user-related data. It has a single method: loadUserByUsername.

    Purpose: Fetch user details from a datasource (database) based on username. Implementation: Implement this to load users from your own repository.

    PasswordEncoder

    The PasswordEncoder interface is used for encoding and validating passwords. It has methods for encoding raw passwords and matching encoded passwords.

    Purpose: Securely hash passwords before storing and verify during authentication. Common Implementations: BCryptPasswordEncoder, Pbkdf2PasswordEncoder, SCryptPasswordEncoder.

    Implementing Core Components
    // 1. Implementing UserDetails on your User Entity@EntitypublicclassUserimplementsUserDetails{@Id@GeneratedValueprivateLong id;privateString email;privateString password;@ManyToMany(fetch =FetchType.EAGER)privateSet<Role> roles;@OverridepublicCollection<?extendsGrantedAuthority>getAuthorities(){return roles.stream().map(role ->newSimpleGrantedAuthority(role.getName())).collect(Collectors.toList());}@OverridepublicStringgetUsername(){return email;}@OverridepublicStringgetPassword(){return password;}@OverridepublicbooleanisAccountNonExpired(){returntrue;}@OverridepublicbooleanisAccountNonLocked(){returntrue;}@OverridepublicbooleanisCredentialsNonExpired(){returntrue;}@OverridepublicbooleanisEnabled(){returntrue;}}// 2. Implementing UserDetailsService@Service@RequiredArgsConstructorpublicclassCustomUserDetailsServiceimplementsUserDetailsService{privatefinalUserRepository userRepository;@OverridepublicUserDetailsloadUserByUsername(String username)throwsUsernameNotFoundException{return userRepository.findByEmail(username).orElseThrow(()->newUsernameNotFoundException("User not found: "+ username));}}// 3. Password Encoder Bean@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}

    Authentication Flow

    When a user attempts to authenticate, the request flows through several components. Understanding this flow helps you customize authentication behavior and debug issues.

    Authentication Flow:
    ═══════════════════════════════════════════════════════════════════
    1. User submits credentials (username/password)
    │
    ▼
    ┌────────────────────────────────────┐
    │   UsernamePasswordAuthFilter       │
    │   Extracts credentials from        │
    │   request and creates              │
    │   Authentication token             │
    └─────────────────┬──────────────────┘
    │
    ▼
    ┌────────────────────────────────────┐
    │   AuthenticationManager            │
    │   Delegates to appropriate         │
    │   AuthenticationProvider           │
    └─────────────────┬──────────────────┘
    │
    ▼
    ┌────────────────────────────────────┐
    │   AuthenticationProvider           │
    │   (e.g., DaoAuthenticationProvider)│
    │                                    │
    │   1. Calls UserDetailsService      │
    │      to load user                  │
    │   2. Uses PasswordEncoder to       │
    │      verify password               │
    └─────────────────┬──────────────────┘
    │
    ┌──────────┴──────────┐
    ▼                     ▼
    ┌─────────────┐       ┌─────────────┐
    │   SUCCESS   │       │   FAILURE   │
    │             │       │             │
    │ Populate    │       │ Throw       │
    │ Security    │       │ Auth        │
    │ Context     │       │ Exception   │
    └─────────────┘       └─────────────┘
    ═══════════════════════════════════════════════════════════════════

    💬 Comments & Discussion