Security Architecture
Spring Security filter chain, AuthenticationManager, AuthenticationProvider, UserDetailsService
- Trace a login request through the entire Spring Security filter chain
- Understand the role of AuthenticationManager and ProviderManager
- Implement a custom UserDetailsService backed by the database
A complete, professional study guide based on the "Concept and Coding" Spring Boot Security lecture series — Part 1: Architecture.
Table of Contents
- Prerequisites
- Authentication vs Authorization
- Where Spring Security Fits — The Filter Chain
- Security Filter Chain
- Authentication Manager & Provider Manager
- Authentication Providers
- UserDetailsService & Password Encoding
- The Authentication Object
- Security Context
- Full Request Flow — End to End
- Architecture as a Template for Each Auth Method
- Setting Up Spring Security — Dependencies
- Diagrams
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Comparison Tables
- Practice Questions
- Summary
1. Prerequisites
What You Should Know Before This Topic
Before studying Spring Boot Security architecture, you should be familiar with:
- Java Servlet Filters — what they are, how they intercept HTTP requests, and how the filter chain works.
- Dispatcher Servlet — how Spring MVC routes requests through the servlet.
- Spring Interceptors — how they differ from filters and where they sit.
- Common Web Security Attacks — CSRF, XSS, SQL Injection. Understanding why we need security makes the architecture more meaningful.
Quick Recap: The Standard Spring MVC Request Flow (No Security)
1HTTP Request2 ↓3Servlet Container (e.g., Tomcat)4 ↓5Filter Chain (Filter 1 → Filter 2 → ... → Filter N)6 ↓7Dispatcher Servlet8 ↓9Interceptors (Pre-handle)10 ↓11Controller (your API / business logic)12 ↓13Interceptors (Post-handle)14 ↓15HTTP ResponseSpring Security does not replace this flow. It integrates into the existing Filter Chain.
2. Authentication vs Authorization
Overview
These are the two foundational pillars of any security system. They are often confused but serve entirely different purposes.
Authentication
Authentication
= Verify WHO you are.
The process of confirming the identity of a user or system. A user proves their identity, typically by providing credentials like a username and password.
Example: You enter your username john@example.com and password secret123. The system verifies these match a known user. If they do — you are authenticated.
Authorization
Authorization
= Check WHAT you are allowed to do.
Even after a user is authenticated (we know who they are), we must determine what resources or actions they are permitted to access.
Example: John is authenticated. But John has the role VIEWER — he can read articles but cannot publish or delete them. That restriction is authorization.
Key Distinction
| Concept | Question Answered | When It Happens | Example |
|---|---|---|---|
| Authentication | Who are you? | First — on login | Username + password check |
| Authorization | What can you do? | After authentication | Role-based access control |
Real-World Analogy
Think of entering a corporate office building:
- Authentication = Showing your employee ID badge at the front desk. Security confirms you work there.
- Authorization = Your ID badge only unlocks the floors you're assigned to. The executive floor requires a higher clearance.
3. Where Spring Security Fits The Filter Chain
The Filter Chain Without Spring Security
Before Spring Security is introduced, a typical Spring Boot app has a filter chain that requests pass through sequentially:
1Servlet Container2 ↓3Filter 1 (e.g., Logging Filter)4 ↓5Filter 2 (e.g., CORS Filter)6 ↓7Filter N8 ↓9Dispatcher Servlet10 ↓11ControllerAdding Spring Security to the Filter Chain
When you add spring-boot-starter-security as a dependency, Spring Security inserts a Security Filter Chain into the existing filter chain. It does not create a parallel system — it plugs into the existing one.
1Servlet Container2 ↓3Filter 14 ↓5Filter 26 ↓7[Security Filter Chain] ← injected by Spring Security8 ↓9Filter N10 ↓11Dispatcher Servlet12 ↓13Controller4. Security Filter Chain
What It Is
The Security Filter Chain is a sequence of security filters that Spring Boot automatically adds to your application's filter pipeline when Spring Security is enabled. Each filter in this chain handles a specific security concern.
Authentication-Method-Specific Filters
Spring Security ships with filters for every major authentication mechanism. However, not all filters are active for every request — only the filters relevant to the authentication method you have configured are invoked.
| Authentication Method | Example Active Filters |
|---|---|
| Form-based login | UsernamePasswordAuthenticationFilter |
| Basic Authentication | BasicAuthenticationFilter |
| JWT (Stateless) | Custom JwtAuthenticationFilter |
| OAuth 2.0 | OAuth2LoginAuthenticationFilter |
How Spring Boot Decides Which Filter to Invoke
Spring Security evaluates incoming requests and routes them through the appropriate filter based on your security configuration (e.g., SecurityFilterChain bean definition). You declare which filters are active via your configuration, and Spring Security respects that during runtime.
Conceptual Visualization
1Security Filter Chain2┌────────────────────────────────────────────┐3│ UsernamePasswordAuthenticationFilter │ ← Form Login only4│ BasicAuthenticationFilter │ ← Basic Auth only5│ BearerTokenAuthenticationFilter (JWT) │ ← JWT only6│ OAuth2LoginAuthenticationFilter │ ← OAuth only7│ CsrfFilter │ ← Active for stateful8│ SessionManagementFilter │ ← Stateful sessions9│ ExceptionTranslationFilter │ ← Always active10│ FilterSecurityInterceptor │ ← Authorization11└────────────────────────────────────────────┘5. Authentication Manager & Provider Manager
The Flow After the Filter
Once a security filter has intercepted the request and identified it as needing authentication, it doesn't perform the authentication itself. Instead, it delegates to the Authentication Manager.
1Security Filter2 ↓3Creates (partially populated) Authentication object4 ↓5Passes to AuthenticationManager.authenticate(Authentication)AuthenticationManager (Interface)
AuthenticationManager is a Spring Security interface with a single method:
1public interface AuthenticationManager {2 Authentication authenticate(Authentication authentication)3 throws AuthenticationException;4}It receives a partially-populated Authentication object (credentials provided, but isAuthenticated = false) and returns a fully-populated one (with roles, and isAuthenticated = true) — or throws an exception if authentication fails.
ProviderManager (Default Implementation)
ProviderManager is the default implementation of AuthenticationManager. Its role is to act as a bridge between the security filter and the correct AuthenticationProvider.
1// Conceptual internal behavior of ProviderManager2for (AuthenticationProvider provider : providers) {3 if (provider.supports(authentication.getClass())) {4 return provider.authenticate(authentication);5 }6}7throw new ProviderNotFoundException("No provider found");It iterates through a list of registered AuthenticationProvider implementations and delegates to the one that supports the type of Authentication object received.
ProviderManager can have a parent AuthenticationManager. If no provider in the current list can handle the authentication, it delegates to the parent. This supports hierarchical security configurations.The Bridge Role of ProviderManager
1Filter (knows: "this is a Form Login request")2 ↓ creates Authentication object3ProviderManager (knows: "Form Login → DaoAuthenticationProvider")4 ↓ delegates to correct provider5DaoAuthenticationProvider (actually performs the verification)6. Authentication Providers
What is an AuthenticationProvider?
An AuthenticationProvider is the component that actually performs the authentication logic. It knows how to verify a specific type of credential.
1public interface AuthenticationProvider {2 Authentication authenticate(Authentication authentication)3 throws AuthenticationException;4
5 boolean supports(Class<?> authentication);6}supports()— tellsProviderManagerwhether this provider can handle the givenAuthenticationtype.authenticate()— performs the actual credential verification and returns a fully authenticatedAuthenticationobject.
Common Providers and Their Roles
| Provider | Authentication Method | What It Does |
|---|---|---|
DaoAuthenticationProvider | Username/Password (Form, Basic) | Verifies password hash, loads user from DB |
JwtAuthenticationProvider | JWT (Stateless) | Validates JWT token signature and claims |
OAuth2LoginAuthenticationProvider | OAuth 2.0 | Handles OAuth authorization code exchange |
DaoAuthenticationProvider (Most Common)
Used for username/password-based authentication (both form login and basic auth). It:
- Takes the raw password from the incoming request.
- Encodes it using the configured
PasswordEncoder. - Loads the stored user details using
UserDetailsService. - Compares the encoded incoming password against the stored encoded password.
- Returns a fully authenticated
Authenticationobject if they match.
7. UserDetailsService & Password Encoding
UserDetailsService (Interface)
UserDetailsService is the interface responsible for loading user data from a storage system. DaoAuthenticationProvider calls it to retrieve the stored user (including their hashed password and roles).
1public interface UserDetailsService {2 UserDetails loadUserByUsername(String username)3 throws UsernameNotFoundException;4}It returns a UserDetails object containing:
- Username
- Password (stored as a hash)
- Granted authorities (roles/permissions)
- Account status flags (expired, locked, enabled)
Two Built-in Implementations
| Implementation | Storage | Use Case |
|---|---|---|
InMemoryUserDetailsManager | Application memory (in-memory) | Development, testing, demos |
JdbcUserDetailsManager | Relational database (via JDBC) | Production applications |
InMemoryUserDetailsManager stores users only while the application is running. All user data is lost on restart. Never use it for production.Custom Implementation (Most Common in Production)
In real-world Spring Boot apps, you typically write your own UserDetailsService implementation that loads users from a custom JPA repository:
1@Service2public class CustomUserDetailsService implements UserDetailsService {3
4 @Autowired5 private UserRepository userRepository;6
7 @Override8 public UserDetails loadUserByUsername(String username)9 throws UsernameNotFoundException {10 User user = userRepository.findByUsername(username)11 .orElseThrow(() ->12 new UsernameNotFoundException("User not found: " + username));13
14 return org.springframework.security.core.userdetails.User15 .withUsername(user.getUsername())16 .password(user.getPassword()) // already hashed17 .roles(user.getRole())18 .build();19 }20}Password Encoding
PasswordEncoder in all authentication configurations.The most commonly used encoder is BCryptPasswordEncoder:
1@Bean2public PasswordEncoder passwordEncoder() {3 return new BCryptPasswordEncoder();4}◆ How Password Encoding Works
During Registration (storing the user):
1raw password: "secret123"2 ↓ BCryptPasswordEncoder.encode()3stored hash: "$2a$10$EixZaYVK1fsbw1Zfbx3OXePaWxn96p36..."`During Login (verifying the user):
1incoming raw password: "secret123"2stored hash: "$2a$10$EixZaYVK1fsbw1Zfbx3OX..."3 ↓ BCryptPasswordEncoder.matches(raw, hash)4result: true → authenticated ✅matches() method handles this correctly.8. The Authentication Object
What Is It?
The Authentication interface is the central data object passed through the entire security pipeline — from filter → provider manager → provider → security context.
1public interface Authentication extends Principal, Serializable {2 Collection<? extends GrantedAuthority> getAuthorities();3 Object getCredentials(); // password / token4 Object getDetails(); // additional request info5 Object getPrincipal(); // the authenticated entity (username or UserDetails)6 boolean isAuthenticated();7 void setAuthenticated(boolean isAuthenticated);8}Lifecycle of the Authentication Object
| Stage | isAuthenticated | Contents |
|---|---|---|
| Created by Filter | false | Username + raw password (partial) |
After ProviderManager delegates | false (still in progress) | Passed to provider |
After AuthenticationProvider succeeds | true | Username, roles, no raw password |
Stored in SecurityContext | true | Complete principal + authorities |
Authentication object for security reasons before it is stored in the SecurityContext.Example: Before and After Authentication
Before (created by filter):
1{2 "principal": "john@example.com",3 "credentials": "secret123",4 "authorities": [],5 "isAuthenticated": false6}After (returned by DaoAuthenticationProvider):
1{2 "principal": { "username": "john@example.com", "roles": ["ROLE_USER"] },3 "credentials": null,4 "authorities": ["ROLE_USER"],5 "isAuthenticated": true6}9. Security Context
What Is It?
The SecurityContext is a thread-local storage that holds the Authentication object for the currently authenticated user, for the duration of a request.
1public interface SecurityContext extends Serializable {2 Authentication getAuthentication();3 void setAuthentication(Authentication authentication);4}SecurityContextHolder
The SecurityContextHolder is the mechanism through which the SecurityContext is stored and accessed. By default, it uses a ThreadLocal strategy — meaning each thread (each HTTP request) has its own isolated security context.
1// Accessing the current authenticated user anywhere in your app2Authentication auth = SecurityContextHolder.getContext().getAuthentication();3String username = auth.getName();4Collection<? extends GrantedAuthority> roles = auth.getAuthorities();What Happens After the Filter Stores the Authentication
Once the filter receives the fully authenticated Authentication object from AuthenticationManager:
- It stores it in the
SecurityContextviaSecurityContextHolder. - The request continues through the filter chain → Dispatcher Servlet → Interceptors → Controller.
- At every point in that chain, including your controller, the
SecurityContextis accessible.
1// In your Controller — accessing authenticated user2@GetMapping("/profile")3public ResponseEntity<String> getProfile() {4 Authentication auth = SecurityContextHolder.getContext().getAuthentication();5 String username = auth.getName(); // "john@example.com"6 return ResponseEntity.ok("Hello, " + username);7}What Happens on Authentication Failure
If the AuthenticationProvider cannot verify the credentials, it throws BadCredentialsException (or another AuthenticationException subclass). The filter catches this and:
- Does NOT store anything in
SecurityContext. - Returns an appropriate HTTP error response (typically
401 Unauthorized).
10. Full Request Flow End to End
Complete Architecture Flow
1Incoming HTTP Request2 ↓3Servlet Container (Tomcat)4 ↓5General Filter Chain (Logging, CORS, etc.)6 ↓7Security Filter Chain8 ↓9 [Relevant Authentication Filter invoked]10 (e.g., BasicAuthenticationFilter / UsernamePasswordAuthenticationFilter)11 ↓12 Creates Authentication object { isAuthenticated: false }13 ↓14 AuthenticationManager.authenticate(authObject)15 ↓16 ProviderManager (bridge — selects appropriate provider)17 ↓18 AuthenticationProvider (e.g., DaoAuthenticationProvider)19 ├─→ PasswordEncoder (hash & compare password)20 └─→ UserDetailsService (load user from memory/DB)21 ↓22 Returns Authentication object { isAuthenticated: true, roles: [...] }23 ↓24 ProviderManager returns to Filter25 ↓26 ┌─────────────────────────────────────────┐27 │ Authentication Success? │28 │ YES → Store in SecurityContextHolder │29 │ NO → Throw BadCredentialsException (401)│30 └─────────────────────────────────────────┘31 ↓ (on success)32Dispatcher Servlet33 ↓34Interceptors35 ↓36Controller (SecurityContext accessible here)37 ↓38HTTP Response11. Architecture as a Template for Each Auth Method
The Base Architecture is Universal
The architecture described above is a template — a base pattern that applies to every authentication method Spring Security supports. Each method (Form Login, Basic Auth, JWT, OAuth) uses the same architecture but with different components plugged in at each stage.
What Changes Per Authentication Method
| Stage | Form Login | Basic Auth | JWT | OAuth 2.0 |
|---|---|---|---|---|
| Filter | UsernamePasswordAuthenticationFilter | BasicAuthenticationFilter | Custom JwtFilter | OAuth2LoginAuthenticationFilter |
| Auth Object Created | UsernamePasswordAuthenticationToken | UsernamePasswordAuthenticationToken | BearerTokenAuthenticationToken | OAuth2LoginAuthenticationToken |
| Provider | DaoAuthenticationProvider | DaoAuthenticationProvider | JwtAuthenticationProvider | OAuth2LoginAuthenticationProvider |
| Extra Steps | Redirect to login page | Base64 decode header | Validate JWT signature & claims | Authorization code exchange |
| Session | Stateful (stores session) | Stateless | Stateless | Depends |
| SecurityContext stored? | Yes | Yes | Yes | Yes |
What We'll Explore Per Authentication Method
For each authentication type covered in the series:
- Which specific filter gets invoked
- What the
Authenticationobject looks like at each stage - Which provider is delegated to
- What the provider does internally
- What gets stored in the SecurityContext
- How the controller uses the security context
12. Setting Up Spring Security Dependencies
Maven Dependencies
1<!-- pom.xml -->2
3<!-- Required: Core Spring Security dependency -->4<!-- Provides: filter chain, authentication manager, providers, annotations -->5<dependency>6 <groupId>org.springframework.boot</groupId>7 <artifactId>spring-boot-starter-security</artifactId>8</dependency>9
10<!-- Optional: Only if you want DB-backed HTTP session storage -->11<!-- Required for: Stateful session-based auth with session stored in DB -->12<dependency>13 <groupId>org.springframework.session</groupId>14 <artifactId>spring-session-jdbc</artifactId>15</dependency>What `spring-boot-starter-security` Provides
Adding this single dependency gives you:
- The entire Security Filter Chain infrastructure
AuthenticationManagerandProviderManager- Default
AuthenticationProviderimplementations (DaoAuthenticationProvider, etc.) UserDetailsServiceinterface + in-memory and JDBC implementationsPasswordEncodersupport (BCrypt, etc.)- Auto-configured basic security (a generated password printed to console on startup)
- CSRF protection (enabled by default for stateful apps)
- Endpoint
/logout(configured by default for form login)
What `spring-session-jdbc` Provides
- Stores HTTP sessions in a relational database table.
- Allows session persistence across application restarts.
- Enables session sharing across multiple application instances (for clustered deployments).
spring-session-jdbc is only needed for stateful (session-based) authentication where you want sessions stored in the DB. For stateless authentication (JWT, OAuth), it is not needed.Setting Up via Spring Initializr
When creating a new project at start.spring.io:
- Add Spring Web — for REST controllers and MVC.
- Add Spring Security — for authentication/authorization infrastructure.
- Optionally add Spring Session JDBC — only for DB-backed session storage.
What Happens on First Run (Default Behavior)
Once spring-boot-starter-security is on the classpath with no custom configuration:
- All endpoints are protected (returns 401/redirect to login for unauthenticated requests).
- A default login page is served at
/login. - A default user
useris created with a randomly generated password printed to the console:
1Using generated security password: 3f7e9a2c-81b4-4d5a-9e12-a2f8c3d7e4b1UserDetailsService and SecurityFilterChain configuration before going to production.13. Diagrams
Full Architecture Mind Map
Component Relationship Diagram
Request State Machine
14. Key Observations
- Spring Security is filter-based. It integrates into the existing Servlet filter chain — it does not replace it.
- Not all security filters run for every request. Only the filters matching the configured authentication method are invoked.
AuthenticationManageris an interface.ProviderManageris its default implementation and acts as a bridge between filters and providers.AuthenticationProviderdoes the actual work.ProviderManagerjust routes to the right one.- The
Authenticationobject travels the pipeline. It starts partial (isAuthenticated = false) and ends complete (isAuthenticated = true) — or an exception is thrown. - Security context is thread-local. Each request thread has its own security context, keeping users isolated.
- Passwords must always be hashed. Spring Security enforces use of
PasswordEncoderand never compares raw passwords. - This architecture is a template. Form Login, Basic Auth, JWT, and OAuth all follow the same base structure with different components swapped in.
spring-session-jdbcis optional and only needed for database-persisted HTTP sessions (stateful auth).
15. Common Mistakes
Mistake 1: Confusing Authentication and Authorization
1// ❌ Wrong thinking:2"The user is blocked — must be an authentication error"3// Could be an authorization error (user authenticated but lacks permission)Fix: Check the HTTP status code — 401 Unauthorized = authentication failure. 403 Forbidden = authorization failure.
Mistake 2: Assuming all security filters run for every request
1// ❌ Wrong assumption:2"Every request runs through ALL security filters"Fix: Only the filter(s) matching your configured authentication method are invoked per request.
Mistake 3: Storing raw passwords
1// ❌ Never do this2user.setPassword(rawPassword); // storing plain text3userRepo.save(user);1// ✅ Always encode2user.setPassword(passwordEncoder.encode(rawPassword));3userRepo.save(user);Mistake 4: Not understanding that `SecurityContext` is thread-local
1// ❌ Dangerous: sharing security context across threads without care2CompletableFuture.runAsync(() -> {3 // SecurityContextHolder may be empty here in a new thread!4 Authentication auth = SecurityContextHolder.getContext().getAuthentication();5});Fix: Use SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL) or explicitly pass the Authentication object when using async operations.
Mistake 5: Skipping security architecture study and jumping to implementation
Understanding the full flow (filter → auth manager → provider → security context) prevents confusion when debugging authentication issues in production.
16. Best Practices
- Always implement a custom
UserDetailsServicebacked by your own user repository for production apps.
- Always use
BCryptPasswordEncoder(orArgon2PasswordEncoderfor even stronger security) — never plain text or MD5.
- Follow the principle of least privilege for authorization — grant only the permissions each role genuinely needs.
- Keep the
Authenticationobject clean — after authentication, credentials (raw password/token) should be cleared. Spring Security does this automatically for most providers.
- Do not hardcode credentials in
application.propertiesfor production. Use environment variables or a secrets manager (e.g., AWS Secrets Manager, HashiCorp Vault).
- Understand stateful vs stateless early — choose before designing your security configuration, as it affects session management, CSRF handling, and which providers/filters you need.
- Use
spring-session-jdbconly when needed — for horizontally-scaled apps requiring shared sessions across instances.
- Test your security configuration with Spring Security's test utilities (
@WithMockUser,@WithUserDetails,MockMvcsecurity integration tests).
17. Interview Notes
Commonly Asked Questions
Q: What is the difference between authentication and authorization?
Authentication verifies the identity of a user (who they are). Authorization determines what that authenticated user is allowed to do (what they can access or modify).
Q: Where does Spring Security fit in the Spring Boot request lifecycle?
Spring Security integrates into the Servlet filter chain as a SecurityFilterChain. It sits between the general filters and the Dispatcher Servlet. Requests must pass through the security filters before reaching controllers.
Q: What is ProviderManager and what is its role?
ProviderManager is the default implementation of AuthenticationManager. It acts as a bridge between security filters and AuthenticationProvider implementations. It iterates through registered providers, finds one that supports the given Authentication type, and delegates to it.
Q: What is UserDetailsService and why is it needed?
UserDetailsService is an interface with one method: loadUserByUsername(). It is used by DaoAuthenticationProvider to load stored user data (hashed password, roles) from a data source (in-memory, DB, or custom) so it can verify the incoming credentials.
Q: What is the Authentication object and how does its state change during the request?
Authentication is a Spring Security interface that holds identity information. It starts as a partial object with isAuthenticated = false (created by the filter). After AuthenticationProvider successfully verifies credentials, it is returned as a complete object with isAuthenticated = true and populated roles/authorities.
Q: What is the SecurityContext and how is it accessed?
SecurityContext stores the current Authentication object for the duration of a request. It is held in SecurityContextHolder, which uses a ThreadLocal strategy by default. It can be accessed anywhere in the application via SecurityContextHolder.getContext().getAuthentication().
Q: What HTTP status codes does Spring Security return on failure?
401 Unauthorized— authentication failed (bad credentials, missing token).403 Forbidden— authentication succeeded but authorization failed (insufficient role/permission).
Q: Is spring-session-jdbc always required with Spring Security?
No. It is only needed for stateful (session-based) authentication when you want sessions stored in a database. For stateless authentication (JWT, OAuth), it is not needed.
18. Comparison Tables
Authentication Methods Supported by Spring Security
| Method | Stateful? | Filter Used | Provider Used | Best For |
|---|---|---|---|---|
| Form Login | Yes | UsernamePasswordAuthenticationFilter | DaoAuthenticationProvider | Traditional web apps |
| Basic Auth | No | BasicAuthenticationFilter | DaoAuthenticationProvider | Simple APIs, internal services |
| JWT | No | Custom JWT Filter | Custom JWT Provider | REST APIs, SPAs, mobile |
| OAuth 2.0 | Depends | OAuth2LoginAuthenticationFilter | OAuth2LoginAuthenticationProvider | Social login, SSO |
UserDetailsService Implementations
| Implementation | Storage | Persistence | Use Case |
|---|---|---|---|
InMemoryUserDetailsManager | JVM memory | None (lost on restart) | Development, testing |
JdbcUserDetailsManager | Relational DB | Persistent | Simple production use |
| Custom (JPA-based) | Any (JPA/NoSQL/LDAP) | Persistent | Most real-world apps |
`AuthenticationManager` vs `AuthenticationProvider`
| Aspect | AuthenticationManager | AuthenticationProvider |
|---|---|---|
| Role | Routes to the right provider | Actually performs authentication |
| Implementation | ProviderManager (default) | DaoAuthenticationProvider, etc. |
| Knows about filters? | Yes (via delegation chain) | No |
| Knows about users? | No | Yes (via UserDetailsService) |
| Number per app | Typically one | Multiple (one per auth method) |
19. Practice Questions
Easy
- What is the difference between authentication and authorization? Give a real-world example of each.
- What HTTP status code does Spring Security return when authentication fails? When authorization fails?
- Where in the Spring request lifecycle does the Security Filter Chain sit?
- Which class is the default implementation of
AuthenticationManager? - What does
UserDetailsService.loadUserByUsername()return?
Medium
- Trace the complete flow of an HTTP request from the client to the controller when Spring Security is configured with Basic Authentication.
- Explain the lifecycle of the
Authenticationobject from creation to storage inSecurityContext. - What is the role of
ProviderManager? Why is it called a "bridge"? - Why is
spring-session-jdbcnot always required with Spring Security? - What happens internally in
DaoAuthenticationProviderwhen a user logs in with username and password?
Hard
- A user is successfully authenticated (confirmed by logs) but receives a
403 Forbiddenresponse when accessing/admin. What is the most likely cause and how would you investigate? - Explain why not all security filters run for every request. How does Spring Security decide which filters to invoke?
- Your application is deployed across three instances behind a load balancer using stateful session authentication. A user logs in on Instance A but their next request goes to Instance B, which doesn't know about the session. How does
spring-session-jdbcsolve this? - A developer stores user passwords as plain text in the database. Explain all the security risks this introduces and how Spring Security's
PasswordEncoder+ BCrypt mitigates them. - How would the base security architecture diagram change for JWT authentication compared to form-based login? Which components would be the same, and which would be different?
20. Summary
Revision Bullets
- Authentication = verifying identity ("who are you?"). Authorization = checking permissions ("what can you do?").
- Spring Security integrates into the existing Servlet filter chain — it does not replace it.
- The Security Filter Chain is a set of security-specific filters added to the app when Spring Security is enabled.
- Not all security filters run for each request — only the filter(s) for the configured auth method are invoked.
- The
Authenticationobject travels through the pipeline: partial (filter) → fully authenticated (provider) → stored (security context). AuthenticationManageris an interface.ProviderManageris its default implementation — a bridge between filters and providers.AuthenticationProviderperforms the actual credential verification (e.g.,DaoAuthenticationProviderfor username/password).UserDetailsServiceloads stored user data. Built-in:InMemoryUserDetailsManager,JdbcUserDetailsManager. Typically: custom JPA implementation.- Passwords are always hashed — never stored or compared as plain text.
BCryptPasswordEncoderis the standard choice. - On success:
Authenticationstored inSecurityContextHolder(thread-local). On failure:401 Unauthorizedthrown. - The
SecurityContextis accessible throughout the request lifecycle, including in controllers. - This architecture is a base template — each auth method (Form Login, Basic Auth, JWT, OAuth) uses the same structure with different components.
spring-boot-starter-securityprovides the entire infrastructure.spring-session-jdbcis optional and only needed for DB-backed stateful sessions.
Study guide generated from the "Concept and Coding" Spring Boot Security lecture series — Part 1: Architecture.
Mastery check
How well can you recall this?
Finished this lesson?