How Spring Security Handles Authentication – Java Fresher
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
Spring Security authentication is a collaboration between a filter chain, an AuthenticationManager, and one or more AuthenticationProvider implementations. For form or username/password authentication, a filter creates an unauthenticated Authentication object and passes it to ProviderManager. ProviderManager selects a provider that supports that token type.
DaoAuthenticationProvider loads UserDetails and asks PasswordEncoder to compare the submitted password with the stored hash. On success it returns an authenticated result with the principal and authorities, and Spring places it in a SecurityContext for later authorization.
The exact entry and failure behavior depends on the configured mechanism. Form login commonly redirects to a login or failure page. A protected bearer-token API commonly uses an AuthenticationEntryPoint to return 401. Standard JWT bearer validation can be configured with Spring Security OAuth2 Resource Server instead of requiring a custom filter.
How Spring Security Handles Authentication – Java Fresher
Direct Answer
Spring Security authenticates through a SecurityFilterChain chosen for the request. A filter or another authentication mechanism creates an Authentication request and passes it to an AuthenticationManager, commonly ProviderManager. A matching AuthenticationProvider validates it; DaoAuthenticationProvider uses UserDetailsService and PasswordEncoder for username/password authentication. On success, Spring stores the authenticated result in a SecurityContext. Failure handling depends on the mechanism: an API may return 401, while form login commonly redirects to a failure page.
Deep Dive & Architecture
The filter chain does not contain one universal authentication filter. Spring selects a SecurityFilterChain and each configured mechanism contributes its own filter or request converter. UsernamePasswordAuthenticationFilter handles a form-login style request; BasicAuthenticationFilter handles HTTP Basic; BearerTokenAuthenticationFilter handles bearer tokens when Resource Server is configured.
The Authentication object initially carries the supplied credential in an unauthenticated form. ProviderManager asks providers that support its token type. DaoAuthenticationProvider loads UserDetails and validates the password through PasswordEncoder. A successful provider returns an authenticated object whose authorities can be used by authorization.
A SecurityContextRepository decides whether the context is saved between requests. A session-based login can persist it in an HTTP session. With a stateless bearer API, the context is normally rebuilt for each request and cleared afterward. Failure is handed to the mechanism's configured handler, so it is not universally a 401 response.
Code Example
@Service
public class JpaUserDetailsService implements UserDetailsService {
private final UserRepository repo;
JpaUserDetailsService(UserRepository repo) { this.repo = repo; }
@Override
public UserDetails loadUserByUsername(String username) {
User u = repo.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(username));
return org.springframework.security.core.userdetails.User
.withUsername(u.getUsername())
.password(u.getPasswordHash()) // BCrypt hash from DB
.authorities("ROLE_" + u.getRole())
.build();
}
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // DaoAuthenticationProvider uses this to verify
}
You supply how to load a user and how to check the password; Spring orchestrates the rest.
Common Mistakes & Pitfalls
- Authenticating in the controller: identity verification belongs in the filter chain, not your handler.
- No
PasswordEncoderbean: causesThere is no PasswordEncoder mapped for the id "null"at runtime. - Comparing raw passwords: never
equals()passwords — usePasswordEncoder.matches. - Returning
nullfromloadUserByUsername: throwUsernameNotFoundExceptioninstead. - Confusing
AuthenticationManagerandAuthenticationProvider: the manager delegates; the provider does the actual check.
Check your understanding
Answer these without looking back at the article.
- What is role-based access control (RBAC) and how do you implement it in Spring Boot?
- What is the difference between authentication and authorization?
- What HTTP status codes should you return for authentication vs authorization failures?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.