How does Spring Security handle authentication and authorization?
How Spring Security handles authentication and authorization: the filter chain, AuthenticationManager, roles, authorities, and @PreAuthorize.
Expected Interview Answer
Spring Security authenticates by verifying who a user is through an AuthenticationManager and its providers, then authorizes by checking whether that authenticated principal has the required roles or permissions to access a resource.
Requests pass through a chain of servlet filters. Authentication is coordinated by the AuthenticationManager, which delegates to AuthenticationProviders (for example a DaoAuthenticationProvider that loads users via UserDetailsService and checks a PasswordEncoder). On success an Authentication object holding the principal and granted authorities is stored in the SecurityContext. Authorization then evaluates those authorities against URL rules in the SecurityFilterChain or method-level annotations like @PreAuthorize, granting or denying access via AccessDecision logic.
- Clear separation of identity (authentication) from permissions (authorization)
- Pluggable providers for form login, OAuth2, JWT, and LDAP
- Centralized filter chain instead of scattered security checks
- Fine-grained URL and method-level access control
- Secure password handling through PasswordEncoder abstractions
AI Mentor Explanation
Authentication is the gate steward checking a player's accreditation pass before a match, confirming identity. Authorization is what that pass allows: a batsman's tag opens the dressing room and pitch, but not the umpires' room. Spring Security first verifies the pass, then checks which areas the pass grants, just as it authenticates a user and then authorizes access to specific resources.
Step-by-Step Explanation
Step 1
Request hits filter chain
The SecurityFilterChain intercepts the request before it reaches the controller.
Step 2
Extract credentials
An authentication filter builds an Authentication token from form data, a JWT, or a basic auth header.
Step 3
Authenticate
AuthenticationManager delegates to a provider that loads the user via UserDetailsService and verifies the PasswordEncoder hash.
Step 4
Store context
On success the populated Authentication with granted authorities is saved in the SecurityContext.
Step 5
Authorize
URL rules and @PreAuthorize checks compare required authorities against the principal to allow or deny access.
What Interviewer Expects
- Clear distinction between authentication and authorization
- Role of the SecurityFilterChain and filters
- AuthenticationManager, providers, and UserDetailsService
- Where authorities and roles are stored and checked
- Awareness of method-level security with @PreAuthorize
Common Mistakes
- Using authentication and authorization as if they mean the same thing
- Storing passwords without a PasswordEncoder
- Thinking security config still needs WebSecurityConfigurerAdapter in modern versions
- Forgetting that the filter chain order matters
- Confusing roles with fine-grained permissions
Best Answer (HR Friendly)
“Spring Security first checks who you are by verifying your login credentials, which is authentication. It then decides what you are allowed to do based on your roles, which is authorization. This keeps identity and permissions cleanly separated and centrally managed.”
Code Example
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}Follow-up Questions
- What is the difference between a role and an authority in Spring Security?
- How does DaoAuthenticationProvider verify a password?
- How would you secure a REST API with JWT in Spring Security?
- What replaced WebSecurityConfigurerAdapter in newer Spring Security versions?
- How does @PreAuthorize differ from URL-based authorization?
MCQ Practice
1. Which component coordinates the authentication process in Spring Security?
AuthenticationManager coordinates authentication by delegating to one or more AuthenticationProviders.
2. Where are a successfully authenticated user's authorities stored?
After authentication, the Authentication object with granted authorities is held in the SecurityContext.
3. Which annotation enables method-level authorization checks?
@PreAuthorize evaluates a security expression before a method runs, enabling fine-grained authorization.
Flash Cards
Authentication vs authorization? — Authentication verifies identity; authorization decides what that identity may access.
What coordinates authentication? — The AuthenticationManager, delegating to AuthenticationProviders.
How are users loaded? — Via UserDetailsService, with passwords checked by a PasswordEncoder.
Where are authorities stored after login? — In the SecurityContext, on the Authentication object.
How is method-level access controlled? — With annotations like @PreAuthorize and @Secured.
Continue Learning
Related Interview Questions
What has to change when migrating an application to Spring Boot 3?
hard
@Async work is losing the security context and swallowing exceptions — how do you configure it correctly?
hard
How would you expose Actuator safely in production?
medium
What is the difference between a servlet filter, a HandlerInterceptor and an aspect, and how do you order them?
medium