AuthenticationManager in Spring Security
AuthenticationManager is the single entry point Spring Security uses to answer one question: are these credentials valid? Login filters call it, and so can your own code. It receives an unauthenticated request, such as a username and password, and returns a fully authenticated user or throws an exception.
In this tutorial you will learn what AuthenticationManager and its main implementation, ProviderManager, do internally. Then you will use it to build a JSON login endpoint for a car-sharing API, including the step that most custom login code forgets: saving the login so the next request remembers it.
1. What Is AuthenticationManager?
AuthenticationManager is an interface with one method:
public interface AuthenticationManager {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
The argument is an Authentication object that holds the submitted credentials and is not yet authenticated. The method has three possible outcomes: return an authenticated Authentication (with authorities), throw an AuthenticationException such as BadCredentialsException when the credentials are wrong, or return null when it cannot decide.
Spring Security almost always uses ProviderManager as the implementation. It does not check passwords itself; it delegates to a list of AuthenticationProvider objects, each specialised for one kind of credential. The overall picture of these components is in Spring Security architecture.
2. Why AuthenticationManager Is Needed
Applications accept credentials in different shapes: a form post, a Basic header, a JSON body, a JWT or an API key. Without a common entry point, each login path would need its own password checks, account-lock checks and event publishing.
AuthenticationManager puts all of that behind one call. The built-in filters use it, and when you need a login path that Spring Security does not provide, such as a JSON login for a single-page app, you call the same manager and get exactly the same checks.
3. How ProviderManager Works
- A caller creates an unauthenticated token, for example
UsernamePasswordAuthenticationToken.unauthenticated(username, password), and passes it toauthenticate. ProviderManagerloops over its providers and skips any whosesupports(Class)method returns false for this token type.- The first provider that returns an authenticated result wins. If a provider throws an
AuthenticationException,ProviderManagerremembers it and tries the remaining providers. - If no provider decides, the optional parent manager is asked. If still nothing succeeds, the remembered exception (or a
ProviderNotFoundException) is thrown. - On success,
ProviderManagererases the credentials (the password) from the result by default and publishes an authentication success event.
4. Important Classes and Methods
| Type | Role |
|---|---|
AuthenticationManager | The interface: authenticate(Authentication) |
ProviderManager | Standard implementation that delegates to a list of providers and an optional parent |
AuthenticationProvider | Validates one kind of token; declares what it handles with supports(Class) |
UsernamePasswordAuthenticationToken | Token for username and password; create it with unauthenticated(...) |
AuthenticationException | Base class of BadCredentialsException, DisabledException, LockedException and others |
AuthenticationConfiguration | Gives access to the manager Spring Boot builds, via getAuthenticationManager() |
SecurityContextRepository | Saves the authenticated context between requests, for example in the HTTP session |
AuthenticationManager as a bean that you can inject by default. Either declare it yourself, as in the example below, or obtain it from AuthenticationConfiguration.5. A Complete Example: JSON Login for a Car-Sharing App
A car-sharing single-page app posts JSON to /api/login and then uses the session cookie for later calls, such as listing the user's trips. Because the browser holds a session cookie, CSRF protection stays on: the app first reads a CSRF token from /api/csrf. Built with Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.
package com.javabytechie.carshare;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/csrf", "/api/login", "/error").permitAll()
.anyRequest().authenticated())
// An API answers 401 instead of redirecting to a login page
.exceptionHandling(ex -> ex
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)));
return http.build();
}
@Bean
AuthenticationManager authenticationManager(UserDetailsService users, PasswordEncoder encoder) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(users);
provider.setPasswordEncoder(encoder);
return new ProviderManager(provider);
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo user only; real users come from a database
return new InMemoryUserDetailsManager(
User.withUsername("leela").password(encoder.encode("leela-pass")).roles("DRIVER").build());
}
}
package com.javabytechie.carshare;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
public record LoginRequest(String username, String password) {}
private final AuthenticationManager authenticationManager;
private final SecurityContextRepository contextRepository = new HttpSessionSecurityContextRepository();
private final SecurityContextHolderStrategy holder = SecurityContextHolder.getContextHolderStrategy();
public LoginController(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
// The single-page app reads this token and sends it back in the X-CSRF-TOKEN header
@GetMapping("/api/csrf")
public Map<String, String> csrf(CsrfToken token) {
return Map.of("headerName", token.getHeaderName(), "token", token.getToken());
}
@PostMapping("/api/login")
public Map<String, Object> login(@RequestBody LoginRequest body,
HttpServletRequest request, HttpServletResponse response) {
Authentication result = authenticationManager.authenticate(
UsernamePasswordAuthenticationToken.unauthenticated(body.username(), body.password()));
request.changeSessionId(); // defend against session fixation
SecurityContext context = holder.createEmptyContext();
context.setAuthentication(result);
holder.setContext(context);
contextRepository.saveContext(context, request, response); // remember the login
return Map.of("user", result.getName(), "authenticated", result.isAuthenticated());
}
@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Map<String, String> loginFailed(AuthenticationException ex) {
// Same message for unknown users and wrong passwords
return Map.of("error", "Invalid username or password");
}
}
package com.javabytechie.carshare;
import java.security.Principal;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TripController {
@GetMapping("/api/trips")
public List<String> trips(Principal principal) {
return List.of(principal.getName() + ": Indiranagar to Airport, 38 km");
}
}
package com.javabytechie.carshare;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CarShareApplication {
public static void main(String[] args) {
SpringApplication.run(CarShareApplication.class, args);
}
}
6. Step-by-Step Code Explanation
- Declaring the manager. The
authenticationManagerbean wraps aDaoAuthenticationProvider, which loads users from theUserDetailsServiceand checks the password with thePasswordEncoder. Declaring the bean makes it injectable into the controller. - Creating the request token.
UsernamePasswordAuthenticationToken.unauthenticated(...)builds a token whoseisAuthenticated()is false. Passing an already-authenticated token would be a security bug, which is why this factory method exists. - Handling failure. When the password is wrong,
authenticatethrowsBadCredentialsException. The@ExceptionHandlerturns everyAuthenticationExceptioninto a 401 with a generic message, so attackers cannot learn whether a username exists. - Saving the login. A successful
authenticatecall does not log anyone in by itself. The controller puts the result into a newSecurityContextand saves it withHttpSessionSecurityContextRepository. Since Spring Security 6, this explicit save is required; without it, the next request is anonymous again. - Changing the session ID. Built-in login filters protect against session fixation automatically. A hand-written login must do it itself, here with
request.changeSessionId(). - CSRF stays on. The login request carries the CSRF token from
/api/csrf. A request without it is rejected before the controller runs.
7. Expected Output
The commands below save cookies to cookies.txt between calls, as a browser would:
$ TOKEN=$(curl -s -c cookies.txt localhost:8080/api/csrf | jq -r .token)
$ curl -b cookies.txt -c cookies.txt -X POST localhost:8080/api/login -H "X-CSRF-TOKEN: $TOKEN" -H 'Content-Type: application/json' -d '{"username":"leela","password":"wrong-pass"}'
HTTP/1.1 401
{"error":"Invalid username or password"}
$ curl -b cookies.txt -c cookies.txt -X POST localhost:8080/api/login -H "X-CSRF-TOKEN: $TOKEN" -H 'Content-Type: application/json' -d '{"username":"leela","password":"leela-pass"}'
HTTP/1.1 200
{"authenticated":true,"user":"leela"}
$ curl -b cookies.txt localhost:8080/api/trips
HTTP/1.1 200
["leela: Indiranagar to Airport, 38 km"]
$ curl localhost:8080/api/trips
HTTP/1.1 401
$ curl -b cookies.txt -X POST localhost:8080/api/login -H 'Content-Type: application/json' -d '{"username":"leela","password":"leela-pass"}'
HTTP/1.1 403
{"timestamp":"2026-11-18T12:13:45.778Z","status":403,"error":"Forbidden","path":"/api/login"}
The wrong password produces the generic 401 message. The correct password returns 200, and from then on the session cookie alone is enough to list trips. A request without the cookie is anonymous and gets 401 from the entry point. The final login attempt omits the CSRF header and is rejected with 403 before AuthenticationManager is even called.
8. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| One consistent entry point for every credential type | Calling it directly means you take over work the filters normally do: saving the context, session fixation, events |
| Providers can be added without touching callers | Not exposed as a bean by default, which confuses many first-time users |
| Parent managers allow shared fallback authentication | A misconfigured parent can create surprising fallbacks or loops |
| Throws typed exceptions that map cleanly to 401 responses | Error messages must be kept generic by you |
9. Common Mistakes and Best Practices
- Not saving the
SecurityContext. SettingSecurityContextHolderlasts only for the current request. Save it with aSecurityContextRepositorywhen you want a session login. - Creating a second
ProviderManagerby accident. If you declare anAuthenticationManagerbean, make sure it contains every provider your filters need, because Spring Security uses your bean. - Leaking whether a user exists. Return the same message for unknown users and wrong passwords.
DaoAuthenticationProvideralso hides missing users asBadCredentialsExceptionby default. - Disabling CSRF for a session-based JSON login. A browser sends the session cookie automatically, so the login and every later state-changing call need CSRF protection.
- Prefer built-in login when it fits.
formLogin()andhttpBasic()already do everything the controller above does manually. Write your own endpoint only when the request format really differs.
10. Summary
AuthenticationManager.authenticateturns an unauthenticated token into an authenticated one or throws anAuthenticationException.ProviderManagerdelegates to the providers that support the token type and falls back to an optional parent.- The manager is not an injectable bean by default; declare one or use
AuthenticationConfiguration. - A custom login endpoint must save the
SecurityContextand change the session ID itself. - Keep failure messages generic and keep CSRF protection for cookie-based logins.
11. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between AuthenticationManager and AuthenticationProvider?
AuthenticationManager is the entry point that callers use. AuthenticationProvider is a pluggable strategy that validates one kind of token. ProviderManager, the standard manager, holds a list of providers and asks each one that supports the token.
Q2. How do I get an AuthenticationManager bean in Spring Boot 3 or 4?
Declare it yourself, for example new ProviderManager(daoAuthenticationProvider), or inject AuthenticationConfiguration and call getAuthenticationManager(). Spring Security does not register one for injection by default.
Q3. Why is the user logged out on the next request after a custom login?
Since Spring Security 6, setting SecurityContextHolder is not saved automatically. Save the context with a SecurityContextRepository, such as HttpSessionSecurityContextRepository, as part of the login.
Q4. What happens when no provider supports the authentication token?
ProviderManager asks its parent manager if one is configured. If nothing can handle the token, it throws ProviderNotFoundException.
Q5. Does ProviderManager remove the password after login?
Yes. By default eraseCredentialsAfterAuthentication is true, so the credentials are cleared from the returned Authentication once authentication succeeds.