Video in progress
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:
- A filter (for example
UsernamePasswordAuthenticationFilter) takes the login and password from the request and creates an unauthenticatedUsernamePasswordAuthenticationToken. - It passes it to
AuthenticationManager.authenticate(). ProviderManagerloops through the list of providers: the one whosesupports(token.getClass())returns true takes over.DaoAuthenticationProviderloads the user from theUserDetailsServiceand compares the password with thePasswordEncoder.- On success, a new
Authenticationfilled in with the authorities comes back and is written into theSecurityContext.
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.
Sign up to mark studied questions and save your progress.