Definition
- AuthenticationProvider – an interface with
authenticate(Authentication)andsupports(Class>)methods; each provider handles one authentication mechanism. - DaoAuthenticationProvider – the standard provider for username/password; loads user details via UserDetailsService and verifies the password with PasswordEncoder.
- supports() – returns true if the provider can handle the given Authentication token type (e.g., UsernamePasswordAuthenticationToken).
- Custom provider – you implement AuthenticationProvider when you need non-standard authentication like OTP, API key, or hardware token verification.
- ProviderManager – calls each registered provider's
supports()and delegatesauthenticate()to the first matching one.
In a bank, different verification methods require different specialists. A teller verifies your signature (username/password, handled by DaoAuthenticationProvider). The digital banking team verifies your OTP (custom OTP provider). The corporate desk verifies your company seal and director authorization (custom corporate provider). Each specialist knows one method. The branch manager (ProviderManager) routes you to the right specialist based on what credentials you present.
Understanding the Concepts
What is AuthenticationProvider?
AuthenticationProvider is the interface that does the actual work of verifying credentials. While AuthenticationManager is the coordinator, AuthenticationProvider is the worker.
public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
}
The supports() method tells ProviderManager whether this provider can handle the given token type. The authenticate() method performs the verification and returns a fully authenticated token or throws an exception.
How does DaoAuthenticationProvider work?
DaoAuthenticationProvider is the default provider for username/password authentication. It has two dependencies:
- UserDetailsService – loads user details (username, hashed password, authorities) from a database, LDAP, or any store.
- PasswordEncoder – verifies the submitted raw password against the stored hash.
The internal flow is:
- Receive a
UsernamePasswordAuthenticationToken(unauthenticated). - Extract the username.
- Call
userDetailsService.loadUserByUsername(username). - Call
passwordEncoder.matches(rawPassword, storedHash). - If the password matches, return a new
UsernamePasswordAuthenticationTokenwith the principal and authorities (authenticated). - If the password does not match, throw
BadCredentialsException.
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class BankAuthConfig {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
package com.bank.service;
import com.bank.repository.BankerRepository;
import com.bank.model.Banker;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BankerUserDetailsService implements UserDetailsService {
private final BankerRepository bankerRepository;
public BankerUserDetailsService(BankerRepository bankerRepository) {
this.bankerRepository = bankerRepository;
}
@Override
public UserDetails loadUserByUsername(String username) {
Banker banker = bankerRepository.findByEmployeeId(username)
.orElseThrow(() -> new UsernameNotFoundException(
"Banker not found: " + username
));
return User.builder()
.username(banker.getEmployeeId())
.password(banker.getPasswordHash())
.authorities(banker.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.toList())
.accountLocked(banker.isLocked())
.disabled(!banker.isActive())
.build();
}
}
Spring Boot auto-configures DaoAuthenticationProvider when it finds a UserDetailsService bean and a PasswordEncoder bean. You do not need to register the provider manually.
How do you write a custom AuthenticationProvider?
When the standard providers do not fit, you implement AuthenticationProvider directly. For example, a banking application that authenticates using OTP (one-time password) sent to the customer's phone:
package com.bank.security;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class OtpAuthenticationProvider implements AuthenticationProvider {
private final OtpVerificationService otpService;
private final CustomerRepository customerRepository;
public OtpAuthenticationProvider(OtpVerificationService otpService,
CustomerRepository customerRepository) {
this.otpService = otpService;
this.customerRepository = customerRepository;
}
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
OtpAuthenticationToken otpToken = (OtpAuthenticationToken) authentication;
String phoneNumber = otpToken.getPhoneNumber();
String otp = otpToken.getOtp();
if (!otpService.verify(phoneNumber, otp)) {
throw new BadCredentialsException("Invalid OTP");
}
Customer customer = customerRepository.findByPhone(phoneNumber)
.orElseThrow(() -> new BadCredentialsException(
"Customer not found"
));
return new OtpAuthenticationToken(
customer,
null,
List.of(new SimpleGrantedAuthority("ROLE_CUSTOMER"))
);
}
@Override
public boolean supports(Class<?> authentication) {
return OtpAuthenticationToken.class
.isAssignableFrom(authentication);
}
}
The custom token class:
package com.bank.security;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
public class OtpAuthenticationToken extends AbstractAuthenticationToken {
private final String phoneNumber;
private final String otp;
private final Object principal;
// Unauthenticated constructor
public OtpAuthenticationToken(String phoneNumber, String otp) {
super(null);
this.phoneNumber = phoneNumber;
this.otp = otp;
this.principal = phoneNumber;
setAuthenticated(false);
}
// Authenticated constructor
public OtpAuthenticationToken(Object principal, String otp,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.phoneNumber = null;
this.otp = otp;
this.principal = principal;
setAuthenticated(true);
}
public String getPhoneNumber() { return phoneNumber; }
public String getOtp() { return otp; }
@Override
public Object getCredentials() { return otp; }
@Override
public Object getPrincipal() { return principal; }
}
What is the difference between AuthenticationProvider and UserDetailsService?
| Aspect | AuthenticationProvider | UserDetailsService |
|---|---|---|
| Role | Performs the full authentication (load + verify) | Only loads user details; does NOT verify the password |
| Interface | authenticate() + supports() | loadUserByUsername() |
| Password check | Yes, the provider verifies credentials | No, DaoAuthenticationProvider calls PasswordEncoder separately |
| When to implement | Non-standard authentication (OTP, API key, hardware token) | Standard username/password authentication |
| Flexibility | Full control over the authentication process | Limited to loading user data |
For most applications, implementing UserDetailsService is sufficient. DaoAuthenticationProvider handles the rest. Implement a custom AuthenticationProvider only when the authentication mechanism is non-standard.
How do you register multiple AuthenticationProviders?
When your banking application supports multiple login methods (password, OTP, API key), you register multiple providers. ProviderManager tries each in order.
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
@Configuration
public class MultiProviderConfig {
@Bean
AuthenticationManager authenticationManager(
DaoAuthenticationProvider daoProvider,
OtpAuthenticationProvider otpProvider) {
return new ProviderManager(daoProvider, otpProvider);
}
@Bean
DaoAuthenticationProvider daoProvider(
BankerUserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
}
When a UsernamePasswordAuthenticationToken arrives, ProviderManager calls daoProvider.supports() which returns true, so it delegates to daoProvider. When an OtpAuthenticationToken arrives, daoProvider.supports() returns false, so ProviderManager moves to otpProvider.
When should you write a custom provider vs using UserDetailsService?
| Scenario | Use UserDetailsService | Use custom AuthenticationProvider |
|---|---|---|
| Username + password from database | Yes | No (DaoAuthenticationProvider handles it) |
| OTP verification via SMS | No | Yes (custom token + custom verification) |
| API key authentication | No | Yes (lookup key in database, no password check) |
| LDAP authentication | No | Use LdapAuthenticationProvider |
| Multi-factor (password + OTP) | No | Yes (verify both factors in one provider) |
| External identity API call | No | Yes (call external service to verify) |
If DaoAuthenticationProvider (UserDetailsService + PasswordEncoder) covers your use case, do not write a custom provider. Custom providers add complexity and require careful testing.
What are common interview follow-up questions?
- Can a single request trigger multiple providers? No. ProviderManager uses the first provider that supports the token type and succeeds. If it throws an exception, the next supporting provider is tried.
- What happens if all providers fail? ProviderManager throws the last AuthenticationException. If no provider supports the token type, it throws ProviderNotFoundException.
- Can you have a parent AuthenticationManager? Yes. ProviderManager can have a parent. If local providers fail, it delegates to the parent. This is useful for multi-tenant setups with shared and tenant-specific providers.
What are common mistakes?
Registering a provider that does not match any token type:
// WRONG: This provider supports OtpAuthenticationToken
// but the login filter creates UsernamePasswordAuthenticationToken
// Result: ProviderManager skips this provider entirely
@Override
public boolean supports(Class<?> authentication) {
return OtpAuthenticationToken.class.isAssignableFrom(authentication);
}
// The login endpoint creates the wrong token type
Authentication token = new UsernamePasswordAuthenticationToken(
phoneNumber, otp // Wrong token type for OTP
);
The fix is to ensure the filter or login endpoint creates the correct token type that the provider supports.
What should a senior engineer know?
- You can register multiple providers for different authentication flows. ProviderManager tries each one in order.
- DaoAuthenticationProvider hides
UsernameNotFoundExceptionasBadCredentialsExceptionby default to prevent username enumeration. You can change this withsetHideUserNotFoundExceptions(false), but it is not recommended for production. - After successful authentication, DaoAuthenticationProvider calls
additionalAuthenticationChecks()which you can override for custom validation (e.g., checking if the account belongs to a specific branch). - In Spring Boot, if you define a custom AuthenticationProvider bean, it is automatically registered with the auto-configured ProviderManager.
Visual Overview
┌────────────────────────────────────────────┐
│ ProviderManager │
│ (holds list of AuthenticationProviders) │
└──────────────────┬─────────────────────────┘
│
┌──────────────┼──────────────────┐
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌────────────┐
│ DaoAuth │ │ OTP Auth │ │ LDAP Auth │
│ Provider │ │ Provider │ │ Provider │
├───────────┤ ├───────────┤ ├────────────┤
│supports: │ │supports: │ │supports: │
│ Username │ │ OtpAuth │ │ Username │
│ Password │ │ Token │ │ Password │
│ Token │ │ │ │ Token │
├───────────┤ ├───────────┤ ├────────────┤
│Uses: │ │Uses: │ │Uses: │
│ UserDetail│ │ OtpService│ │ LdapContext│
│ Service │ │ Customer │ │ Template │
│ Password │ │ Repository│ │ │
│ Encoder │ │ │ │ │
└───────────┘ └───────────┘ └────────────┘
Key Takeaway
AuthenticationProvider is the interface that does the real work of verifying a user's identity. While AuthenticationManager is the coordinator, each AuthenticationProvider is a specialist that knows how to verify one type of credential.
The most commonly used provider is DaoAuthenticationProvider, which combines UserDetailsService (to load user information) with PasswordEncoder (to verify the password hash). For standard username/password authentication, you only need to define these two beans and Spring Boot wires everything together automatically.
When a banking application needs non-standard authentication, such as OTP verification for Priya's mobile banking login, Rajesh writes a custom AuthenticationProvider. The provider implements the authenticate() method to verify the OTP and the supports() method to declare which token type it handles. A matching custom Authentication token class carries the OTP credentials from the filter to the provider.
The key contract is simple: the supports() method must return true for the token type the filter creates, and the authenticate() method must return a fully populated Authentication on success or throw AuthenticationException on failure. If supports() returns false, ProviderManager skips the provider entirely.
The one sentence to remember: AuthenticationProvider does the actual credential verification for one authentication type, and DaoAuthenticationProvider is the standard one that combines UserDetailsService and PasswordEncoder.
---