Scrivio Interview library
InternalsFoundations6 min read · updated 12 November 2026

How do AuthenticationManager, ProviderManager and AuthenticationProvider work together? What happens when an application supports both username/password and API key authentication?

AuthenticationManager is the single entry point with one method, authenticate(Authentication), which returns an authenticated object or throws an AuthenticationException. ProviderManager is its usual implementation: it walks its list of AuthenticationProvider objects, asks each whose supports() accepts the token type to authenticate, takes the first result, and falls back to a parent AuthenticationManager if none succeeds. To support both username and password and API keys, username and password goes through DaoAuthenticationProvider, while API keys need a filter that builds a custom token and a provider that supports that token type.

Why this question is asked

Almost every application ends up with more than one way to log in: a password for people, an API key or a client certificate for machines, perhaps a token from an identity provider. Interviewers ask how the authentication classes fit together because the design is what makes this easy, and misunderstanding it leads to filters that validate credentials themselves and bypass all of Spring Security's checks and events. In this answer, we will recap what an Authentication object is, look at the three types and how ProviderManager chooses a provider, follow both login methods through the same manager, and finish with what happens to credentials after success.

1A Quick Recap of the Authentication Object

In Spring Security, an Authentication object plays two roles. Before authentication, it is a request: 'here is a username and a password, please check them'. After authentication, it is the result: 'this is alice, and she has these authorities'. The same interface carries both, and isAuthenticated() tells them apart.

Each login method has its own Authentication class, called a token. UsernamePasswordAuthenticationToken carries a username and password. BearerTokenAuthenticationToken carries a JWT. An API key would get its own class, such as ApiKeyAuthenticationToken. The class of the token is what tells Spring Security which kind of credentials it is looking at.

2Three Types With Clear Jobs

AuthenticationManager is an interface with exactly one method. Filters only ever talk to it, and they do not care how it works inside.

Java
public interface AuthenticationManager {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
boolean supports(Class<?> authentication); // can I handle this token type?
}

ProviderManager is the implementation we almost always use. It holds a list of AuthenticationProvider objects and an optional parent AuthenticationManager. A provider knows how to check one kind of credential: DaoAuthenticationProvider checks a username and password against a UserDetailsService and a PasswordEncoder, JwtAuthenticationProvider validates a JWT, and our own provider could check API keys. So the manager is the front desk, and the providers are the specialists behind it.

3How ProviderManager Chooses

When authenticate() is called, ProviderManager loops through its providers in order. It skips any provider whose supports() returns false for the token's class. For a provider that supports it, it calls authenticate(). If the provider returns an authenticated object, that result wins and the loop stops. If it returns null, the provider is saying 'not mine after all', and the loop continues. If it throws an ordinary AuthenticationException, such as BadCredentialsException, the manager remembers it and tries the next provider; account status problems (locked, disabled) are rethrown immediately.

If no provider produced a result and there is a parent manager, ProviderManager asks the parent. In a Spring Boot application, the parent is typically the global manager built from the UserDetailsService bean. If nothing succeeds, it throws the last exception it saw, or ProviderNotFoundException when no provider supported the token at all.

Step throughProviderManager.authenticate(token)
  1. Next provider supports the token type?
    YesCall provider.authenticate()NoSkip it, try the next
  2. Returned an authenticated object?
    YesErase credentials, publish success, return itNoRemember the error, try the next
  3. Any providers left?
    YesLoop againNoAsk the parent manager
  4. Parent returned a result?
    YesReturn itNoThrow the last error or ProviderNotFoundException

4 steps in order. Play them, or step through them one at a time.

The first provider that returns a result wins.

4Username and Password Plus API Keys

Now the scenario: the same application supports form or Basic login for people and an API key header for machines. The username and password path needs nothing new. UsernamePasswordAuthenticationFilter or BasicAuthenticationFilter builds a UsernamePasswordAuthenticationToken and calls the manager, and DaoAuthenticationProvider supports that token type.

The API key path needs two pieces, because no built-in component knows about our header. A filter reads X-Api-Key and turns it into an unauthenticated ApiKeyAuthenticationToken, and a provider whose supports() accepts that class checks the key. We register both providers in one ProviderManager, and each request finds its own specialist by token type.

Java
final class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
private final String key; // the raw key before authentication, null after
private final String clientId; // known only after authentication
ApiKeyAuthenticationToken(String key) { super(List.of()); this.key = key; this.clientId = null; }
ApiKeyAuthenticationToken(String clientId, Collection<? extends GrantedAuthority> authorities) {
super(authorities); this.key = null; this.clientId = clientId; setAuthenticated(true);
}
public Object getCredentials() { return key; }
public Object getPrincipal() { return clientId; }
}
class ApiKeyAuthenticationProvider implements AuthenticationProvider {
public boolean supports(Class<?> type) { return ApiKeyAuthenticationToken.class.isAssignableFrom(type); }
public Authentication authenticate(Authentication a) {
ApiClient client = keys.findByKey((String) a.getCredentials())
.orElseThrow(() -> new BadCredentialsException("Invalid API key"));
return new ApiKeyAuthenticationToken(client.id(), client.authorities());
}
}
@Bean
AuthenticationManager authenticationManager(UserDetailsService users, PasswordEncoder encoder, ApiKeyStore keys) {
DaoAuthenticationProvider dao = new DaoAuthenticationProvider(users); // constructor form in 6.3+; check your version
dao.setPasswordEncoder(encoder);
return new ProviderManager(dao, new ApiKeyAuthenticationProvider(keys));
}
// manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("alice", "pw")) -> DaoAuthenticationProvider
// manager.authenticate(new ApiKeyAuthenticationToken("k_9f...")) -> ApiKeyAuthenticationProvider

Notice that the providers never look at the request. Filters extract credentials from HTTP; providers decide whether credentials are valid. That split is what lets us test a provider with plain objects and reuse it from any filter. Declaring the ProviderManager ourselves also avoids surprises with how Boot builds its global manager when several provider beans exist, which has changed between versions.

5What Happens After Success

Before returning a successful result, ProviderManager does two more things. It publishes an authentication success event through its AuthenticationEventPublisher, which is how audit listeners learn about logins. And, because eraseCredentialsAfterAuthentication is true by default, it calls eraseCredentials() on the result, so the password does not stay in memory, in the session or in a log for longer than needed. That is also why our authenticated API key token stores no key: once authenticated, the credential has done its job.

6Follow-up questions

What is the parent AuthenticationManager for?

It lets several managers share a fallback. Each SecurityFilterChain can have a local manager with its own providers, and the parent, usually the global one built from the UserDetailsService, handles anything the local providers do not. It is also a common source of confusion when a request is authenticated by a provider we did not expect, so it is worth logging which providers exist in each chain.

Why would a provider return null instead of throwing?

Null means 'this token type is mine in general, but this particular request is not', for example a provider that only handles keys with a certain prefix. ProviderManager then tries the next provider. Throwing means 'this is mine and it is wrong', which should normally stop the user from getting in.

Can I just validate the API key inside the filter and set the context myself?

It works, but we lose the separation: no events for auditing, no credential erasure, no reuse of the provider, and the filter has to handle errors and context saving on its own. Going through the AuthenticationManager keeps every login method on the same path.

7Conclusion

In this answer, we saw that an Authentication object is both the request to log in and the result. AuthenticationManager is the single entry point, ProviderManager walks its providers, uses supports() to find those that understand the token type, returns the first result, and falls back to a parent manager. For username and password plus API keys, DaoAuthenticationProvider handles the first, and a custom token, filter and provider handle the second, all registered in one manager. On success, ProviderManager publishes an event and erases the credentials.

What to say in the interviewAbout 90 seconds aloud

Open with

AuthenticationManager is the one entry point filters talk to. It has a single method, authenticate, which takes an Authentication representing the credentials and either returns an authenticated Authentication or throws an AuthenticationException.

Then, if they want more

The usual implementation is ProviderManager, which holds a list of AuthenticationProviders. Each provider is a specialist for one credential type and says so through supports(Class). ProviderManager loops through them, skips those that don't support the token's class, calls the rest, and the first one that returns an authenticated result wins.

If a provider throws bad credentials it remembers the error and tries the next, and if nobody succeeds it asks its parent manager, and finally throws the last error or ProviderNotFoundException. On success it publishes a success event and, by default, erases the credentials from the result.

For an app with both passwords and API keys, the password side is already covered: the form or Basic filter builds a UsernamePasswordAuthenticationToken and DaoAuthenticationProvider checks it with the UserDetailsService and PasswordEncoder.

For API keys I'd write a small custom token class, a filter or converter that reads the header and creates the unauthenticated token, and a provider that supports that class, looks up the key and returns an authenticated token with the client's authorities.

I'd register both providers in one ProviderManager explicitly, so filters stay about HTTP and providers stay about validation.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do AuthenticationManager, ProviderManager and AuthenticationProvider work together?...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/1c2f4c92b8/