Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Authentication Mechanisms

AuthenticationManager, ProviderManager and Custom Providers

See how ProviderManager asks each AuthenticationProvider in turn, how supports() selects one, and how to write a custom provider for one-time codes or API keys.

Every authentication filter ends with the same call: authenticationManager.authenticate(token). What happens behind that call is a small, elegant design. One manager owns a list of providers; each provider knows how to check one kind of credential. Adding a new way to log in (a one-time code, an API key, a corporate directory) means adding a provider, not rewriting the filter.

The real Spring types are shown read-only. The runnable examples are Java stand-ins that follow the same contracts, so you can see the control flow work.

The three types

Java
public interface AuthenticationManager {
    Authentication authenticate(Authentication authentication) throws AuthenticationException;
}

public interface AuthenticationProvider {
    Authentication authenticate(Authentication authentication) throws AuthenticationException;
    boolean supports(Class<?> authentication);
}

ProviderManager is the standard AuthenticationManager. Its algorithm:

  1. For each provider in order, ask supports(token.getClass()). Skip those that say no.
  2. Call authenticate. If it returns an Authentication, stop and return it.
  3. If a provider returns null, it could not decide; try the next one.
  4. If a provider throws an AuthenticationException, remember it and try the next provider. Only account-state exceptions such as AccountStatusException stop the loop immediately.
  5. If none succeeded, try the parent manager (if configured), then throw the last exception (a ProviderNotFoundException if no provider supported the token).
flowchart LR
    F["Authentication filter"] --> PM["ProviderManager"]
    PM --> P1["DaoAuthenticationProvider<br/>supports UsernamePassword"]
    PM --> P2["OneTimeCodeProvider<br/>supports OtpToken"]
    PM --> P3["JwtAuthenticationProvider<br/>supports BearerToken"]
    PM -.->|"if nobody succeeds"| PA["parent manager"]

Each token type has a provider; the manager is only a dispatcher.

Which providers exist in a chain depends on the configuration: formLogin and httpBasic use DaoAuthenticationProvider (it needs a UserDetailsService and a PasswordEncoder); oauth2ResourceServer().jwt() adds JwtAuthenticationProvider; x509, LDAP and others bring theirs.

Tokens: before and after

An Authentication object is used for both the request and the result. Before authentication it carries the claimed identity and credentials (isAuthenticated() is false). A provider returns a new object with the verified principal, the granted authorities and isAuthenticated() == true, and then erases the credentials. Never mark a token authenticated yourself by calling setAuthenticated(true) in a filter; use the factory methods (UsernamePasswordAuthenticationToken.authenticated(...)) inside providers.

A ProviderManager you can run

The stand-in below implements the algorithm above with two token types: a username and password, and a one-time code. Try the order of failure: an unsupported token, a wrong code, an exception that falls through to the next provider.

Java ProviderManager dispatch (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line is the common configuration error: you add a filter that produces an OtpToken but forget to register a provider that supports it, so authentication fails with a ProviderNotFoundException ("No AuthenticationProvider found").

Writing a real custom provider

A one-time-code provider in Spring terms:

Java
@Component
class OtpAuthenticationProvider implements AuthenticationProvider {

    private final OtpService otp;
    private final UserDetailsService users;

    OtpAuthenticationProvider(OtpService otp, UserDetailsService users) {
        this.otp = otp;
        this.users = users;
    }

    @Override
    public Authentication authenticate(Authentication auth) {
        String user = auth.getName();
        String code = (String) auth.getCredentials();
        if (!otp.verify(user, code)) {
            throw new BadCredentialsException("Invalid code");
        }
        UserDetails details = users.loadUserByUsername(user);
        return OtpAuthenticationToken.authenticated(details, details.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> type) {
        return OtpAuthenticationToken.class.isAssignableFrom(type);
    }
}

Registering it for a chain:

Java
http.authenticationProvider(otpAuthenticationProvider);

Rules for a good provider:

  • Return null only for "I cannot decide", otherwise throw. Returning null for a failure silently lets another provider accept.
  • Check supports precisely. Do not return true for Authentication.class or you will receive tokens you cannot understand.
  • Do not log credentials, not even when they fail.
  • Make verification constant-time for secrets.

Bean-defined authentication managers

A plain Boot application usually does not declare an AuthenticationManager at all: Spring builds a ProviderManager from your UserDetailsService and PasswordEncoder beans. If you need it in your own code (for example a JSON login controller that authenticates manually), expose it:

Java
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
}

or build one explicitly for a single chain:

Java
@Bean
AuthenticationManager apiManager(UserDetailsService uds, PasswordEncoder enc) {
    DaoAuthenticationProvider dao = new DaoAuthenticationProvider(uds);
    dao.setPasswordEncoder(enc);
    return new ProviderManager(dao);
}

A controller that logs in by hand must also save the context so the next request is authenticated. The following model shows the pitfall: authentication succeeded, but without saving the SecurityContext the session knows nothing.

Java Manual login: authenticate, then save the context (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In real Spring Security 6 and later, SecurityContextHolder.setContext(...) alone is not enough for the next request: you must call securityContextRepository.saveContext(context, request, response) yourself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ProviderManager do when the first supporting provider throws a BadCredentialsException?

    Only the last exception is thrown if none succeeds. Account-status exceptions are the exception that stop the loop.
  2. 2. What is supports(Class) for?

    The manager asks it first and skips providers that cannot handle the token type.
  3. 3. What happens if you add a filter producing a new token type but no provider supports it?

    A matching provider must be registered, otherwise authentication cannot complete.
  4. 4. After authenticating manually in a controller, what else must you do in Spring Security 6+ for the next request to be authenticated?

    The context is no longer saved automatically at the end of the request, so the controller must save it explicitly.

Summary

  • ProviderManager dispatches an Authentication token to the providers that supports its type and returns the first success.
  • Providers return an authenticated token, throw AuthenticationException, or return null when they cannot decide.
  • Unmatched tokens end in ProviderNotFoundException; register a provider for every token type you create.
  • Expose or build an AuthenticationManager bean when you need it manually, and save the SecurityContext yourself after a manual login.
  • Keep credentials out of logs and compare secrets in constant time.

Next: JDBC user stores