skip to content

AuthenticationManager & ProviderManager

AuthenticationManager is the entry point, ProviderManager delegates to an ordered list of AuthenticationProviders, and each provider says which token types it supports. Knowing this SPI is what lets you plug in a custom mechanism instead of hacking a filter.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What is the contract of AuthenticationManager.authenticate()? What are its three possible outcomes?

level: juniorimportance: must knowfreq 70%

answer

  1. one method: authenticate(Authentication)->Authentication
  2. success / throw AuthenticationException / null
  3. input = unauthenticated, output = authenticated
  4. functional interface
  5. ProviderManager is the impl

basics

~10 s

AuthenticationManager 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 s

AuthenticationManager 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
java
// 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

for a junior

Know the single method, the three outcomes, and that a filter calls it and stores the result in the SecurityContext.

for a middle

Explain the dual role of Authentication (request vs result) and name the common AuthenticationException subtypes.

for a senior

Discuss how to obtain the bean in Spring Security 6 and why the null/throw distinction exists (delegation).

for a principal

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

context

open as a page

How does ProviderManager work? Walk through how it iterates over its AuthenticationProviders and uses the parent manager.

level: middleimportance: must knowfreq 65%

basics

~20 s

ProviderManager is the standard AuthenticationManager. It holds a list of AuthenticationProviders and asks each whether it supports the token; the first one that supports it and returns a non-null result wins. If none succeed, it delegates to an optional parent manager.

open as a page

How do you implement a custom AuthenticationProvider? What must supports() and authenticate() do?

level: middleimportance: should knowfreq 55%

basics

~20 s

Implement AuthenticationProvider with two methods. supports(Class) returns true for the token types you handle. authenticate(Authentication) validates the credentials and returns a new, fully authenticated token with authorities, throws an AuthenticationException on failure, or returns null if it can't handle the request.

open as a page

Explain the parent AuthenticationManager mechanism in ProviderManager and the credential-erasure behavior. Why do they exist?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A ProviderManager can have a parent AuthenticationManager it falls back to when none of its own providers authenticate. This lets multiple filter chains share a common global manager. After a successful authentication, ProviderManager erases the raw credentials from the returned token by default to reduce in-memory exposure.

open as a page

You have two AuthenticationProviders supporting the same token: a primary and a legacy fallback. A user's account is locked. Why might returning DisabledException/LockedException versus BadCredentialsException from the primary produce very different behavior, and how does that inform provider ordering and exception design?

level: principalimportance: nice to knowfreq 25%

basics

~20 s

If the primary throws an AccountStatusException (like LockedException), ProviderManager stops the chain immediately, so the legacy provider never runs and the user sees 'account locked'. If it throws BadCredentialsException, ProviderManager keeps going and the legacy provider may authenticate or reject, changing the outcome and the audit trail.

open as a page