Video in progress

Strong Middle 🌱 Spring

How are AuthenticationManager, ProviderManager and AuthenticationProvider related in Spring Security?

AuthenticationManager is an interface with a single method (authenticate). Its main implementation, ProviderManager, asks several AuthenticationProviders in turn; the first provider that recognizes the token type does the check. Adding a login method means adding a new provider.

📖 Answer

In a login request, the chain goes like this:

  1. A filter (for example UsernamePasswordAuthenticationFilter) takes the login and password from the request and creates an unauthenticated UsernamePasswordAuthenticationToken.
  2. It passes it to AuthenticationManager.authenticate().
  3. ProviderManager loops through the list of providers: the one whose supports(token.getClass()) returns true takes over.
  4. DaoAuthenticationProvider loads the user from the UserDetailsService and compares the password with the PasswordEncoder.
  5. On success, a new Authentication filled in with the authorities comes back and is written into the SecurityContext.

If no provider matches, ProviderManager turns to its parent; if there's none either, ProviderNotFoundException.

Your own provider, for example for signing in with an SMS code:

@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 a) {
        String phone = a.getName();
        if (!otp.verify(phone, (String) a.getCredentials())) {
            throw new BadCredentialsException("Kod noto'g'ri");
        }
        UserDetails u = users.loadUserByUsername(phone);
        return UsernamePasswordAuthenticationToken.authenticated(u, null, u.getAuthorities());
    }

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

This is where people often trip in practice: Spring Boot assembles a provider automatically only if there's a single UserDetailsService. If you declare a provider bean yourself, the default configuration changes, so verify with a test that password login still works.