What is the contract of AuthenticationManager.authenticate()? What are its three possible outcomes?
answer
- one method: authenticate(Authentication)->Authentication
- success / throw AuthenticationException / null
- input = unauthenticated, output = authenticated
- functional interface
- ProviderManager is the impl
basics
~10 sAuthenticationManager has one method, authenticate(Authentication). It returns a fully authenticated Authentication if credentials are valid, throws an AuthenticationException if they are invalid, or returns null if it cannot decide.
solid answer
~30 sAuthenticationManager is a single-method (functional) interface: Authentication authenticate(Authentication authentication) throws AuthenticationException. You pass in an unauthenticated token (e.g. a UsernamePasswordAuthenticationToken carrying the raw username/password). Three outcomes: (1) success — it returns a fully populated Authentication with authorities set and isAuthenticated() true; (2) failure — it throws a subclass of AuthenticationException (BadCredentialsException, DisabledException, etc.); (3) undecided — it returns null, meaning 'I cannot process this type of request', letting a caller try something else. In practice most callers treat null-or-throw the same. Filters like UsernamePasswordAuthenticationFilter call it, then store the returned Authentication in the SecurityContext.
code
java · 19 lines// Programmatic authentication in a custom login endpoint
@RestController
class LoginController {
private final AuthenticationManager authenticationManager;
LoginController(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@PostMapping("/login")
ResponseEntity<Void> login(@RequestBody Credentials creds) {
Authentication request =
new UsernamePasswordAuthenticationToken(creds.username(), creds.password());
// Throws AuthenticationException on bad credentials; returns authenticated token on success
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
return ResponseEntity.ok().build();
}
}go deeper
Know the single method, the three outcomes, and that a filter calls it and stores the result in the SecurityContext.
Explain the dual role of Authentication (request vs result) and name the common AuthenticationException subtypes.
Discuss how to obtain the bean in Spring Security 6 and why the null/throw distinction exists (delegation).
Reason about the contract's role in composability — null enables chaining/parent delegation, exceptions carry status semantics for lockout/audit.
## What AuthenticationManager is `AuthenticationManager` is the central strategy interface in Spring Security for performing authentication. It is a **functional interface** with exactly one method: ```java public interface AuthenticationManager { Authentication authenticate(Authentication authentication) throws AuthenticationException; } ``` An **Authentication** object plays two roles in Spring Security: as *input* it is a request for authentication (an unauthenticated token holding a principal and credentials, e.g. username + raw password); as *output* it represents an authenticated principal (with `getAuthorities()` populated and `isAuthenticated()` returning true). ## The three-outcome contract The Javadoc defines exactly three legal behaviors: 1. **Return a fully authenticated object** (with granted authorities) if the credentials are valid. 2. **Throw an `AuthenticationException`** if the credentials are invalid. `AuthenticationException` is the abstract base of a family: `BadCredentialsException` (wrong password), `DisabledException`, `LockedException`, `AccountExpiredException`, `CredentialsExpiredException` (these four extend `AccountStatusException`), `UsernameNotFoundException`, `ProviderNotFoundException`, etc. 3. **Return `null`** if it cannot decide — meaning this manager doesn't know how to handle that kind of `Authentication`. This is rarely used by application code but is part of the SPI. ## Where it's called Authentication filters obtain an `AuthenticationManager` and call `authenticate()`. For example, `UsernamePasswordAuthenticationFilter.attemptAuthentication()` builds an unauthenticated `UsernamePasswordAuthenticationToken` and passes it in. On success the filter stores the result via `SecurityContextHolder.getContext().setAuthentication(...)`. ## Key gotchas - The **input and output are both `Authentication`** but semantically different (unauthenticated request vs authenticated result). Never trust the incoming `isAuthenticated()` flag — a caller could set it. - `AuthenticationException` is a `RuntimeException`, so it's unchecked despite the `throws` clause. - The manager should **not** return an object with valid authorities unless authentication truly succeeded. - The de-facto standard implementation is `ProviderManager`; you rarely implement `AuthenticationManager` directly. ## When to use You obtain the configured `AuthenticationManager` bean (in modern Spring Security via `AuthenticationConfiguration.getAuthenticationManager()` or by exposing it from your `SecurityFilterChain` config) when you need to authenticate programmatically — for example in a custom login endpoint or a JWT/refresh-token flow.
- How do you obtain the AuthenticationManager bean in modern Spring Security (6.x)?Inject AuthenticationConfiguration and call getAuthenticationManager(), or define a bean that returns the AuthenticationManager built by the HttpSecurity/AuthenticationManagerBuilder. The old WebSecurityConfigurerAdapter.authenticationManagerBean() approach is removed.
- What does isAuthenticated() mean on the input versus the output token?On the input it's typically false (a request to authenticate); on the returned object it's true. You must never trust an incoming true flag as proof of authentication.
saying these in an interview costs you the question
- Saying authenticate() returns a boolean
- Claiming it returns null on failure (failure throws; null means 'undecided')
- Thinking the input Authentication is already authenticated
- Confusing AuthenticationManager (authentication) with AccessDecisionManager/authorization