In Part 1, we understood why Spring Security uses filters, where those filters execute, and how we configure a custom SecurityFilterChain.
Now let's understand what happens when a user tries to log in.
Imagine you are building a login API.
A user sends:
{
"username": "ram",
"password": "r@123"
}
Your application receives these credentials. But how does Spring Security know whether the username exists? How does it compare the password? Who decides whether the user is authenticated?
Does SecurityFilterChain do all of this?
No.
Spring Security divides this responsibility into smaller components:
AuthenticationAuthenticationManagerAuthenticationProviderDaoAuthenticationProviderUserDetailsServicePasswordEncoder
At first, these names might look confusing. But once we follow an actual login request, each component will make sense.
Let's start from the beginning.
Table of contents
- Start with the authentication problem
- Follow the authentication flow
- Understand UserDetails and user storage
- Store passwords safely
- Connect AuthenticationManager to your application
- Connect the flow to your SecurityConfig
- Which one should I use?
- Common mistakes
- Quick recap
- Try it yourself
Start with the authentication problem
Before understanding Spring Security classes, let's understand the actual problem.
Suppose we have a user stored in our database:
Username: ram
Password: $2a$10$someEncodedPassword
Role: USER
A user tries to log in using:
Username: ram
Password: r@123
Our application needs to perform a few operations:
- Find the user named
ram. - Retrieve the user's stored password.
- Compare the submitted password with the stored password.
- Check whether the account is allowed to authenticate.
- If everything is valid, create an authenticated user representation.
- Make that authentication available to the rest of the application.
Spring Security provides different components for these responsibilities.
The important thing to understand is that authentication is a process, not a single class or method.
What does Authentication represent?
In Spring Security, Authentication is an interface that represents the authentication information of a user or an authentication request.
It can represent two different situations:
- Someone is trying to prove their identity.
- Someone has already been authenticated.
For example, when a user submits a username and password, Spring Security can create an Authentication object containing those credentials.
At this stage, the user is not authenticated yet.
After the credentials are verified, Spring Security returns an authenticated Authentication object.
Think of it like entering an office.
You arrive at the office reception
|
v
You provide your ID card
|
v
Reception verifies your identity
|
+------+------+
| |
v v
Valid ID Invalid ID
| |
v v
Entry given Entry denied
The ID card you provide is not proof that your identity has already been verified. It is the information that needs to be checked.
The same idea applies to Spring Security.
Principal, credentials and authorities
An Authentication object contains a few important pieces of information.
Let's understand them using a login example.
Username: ram
Password: r@123
Role: USER
Principal
The principal represents the identity of the user.
For a username/password login, it can initially be the username.
After authentication, it is commonly a UserDetails object containing the user's information.
Credentials
Credentials are the information used to prove the identity.
In our example, the password is the credential.
Authorities
Authorities represent the permissions granted to the authenticated user.
For example:
ROLE_USER
ROLE_ADMIN
A user with ROLE_ADMIN may be allowed to access administrative endpoints, while a user with ROLE_USER may only access normal application features.
Here's a simplified view:
+--------------------------------------+
| Authentication |
+--------------------------------------+
| |
| Principal : ram |
| Credentials : r@123 |
| Authorities : ROLE_USER |
| |
| Authenticated: false / true |
| |
+--------------------------------------+
One more important method is:
authentication.isAuthenticated();
It tells us whether the authentication object represents an authenticated identity.
But don't confuse this flag with password verification performed by your application. A trusted authentication provider should be responsible for producing the authenticated result.
Follow the authentication flow
Now let's connect the components.
Imagine a user submits a username and password.
Spring Security needs someone to receive the authentication request, someone to decide which authentication mechanism should handle it, and someone to verify the actual credentials.
This is where the following components come into the picture:
Username and Password
|
v
Authentication object
|
v
AuthenticationManager
|
v
AuthenticationProvider
|
v
UserDetailsService
|
v
PasswordEncoder
|
v
Authenticated Authentication
Let's understand each component.
Create an unauthenticated Authentication object
Spring Security provides a class called UsernamePasswordAuthenticationToken.
It implements the Authentication interface.
Despite the word Token in its name, this is not a JWT.
It is simply an object used to represent username/password authentication information.
Let's create one:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
public class LoginExample {
public static void main(String[] args) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
"ram",
"r@123"
);
System.out.println(authentication.getPrincipal());
System.out.println(authentication.getCredentials());
System.out.println(authentication.isAuthenticated());
}
}
Output:
ram
r@123
false
Notice the last output:
false
Why?
Because we have only created an authentication request. We haven't verified the credentials yet.
There are two constructors worth knowing:
1. Unauthenticated constructor
new UsernamePasswordAuthenticationToken(
username,
password
);
This creates an unauthenticated authentication object.
2. Authenticated constructor
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
This constructor creates an authenticated object containing the user's authorities.
The second constructor is intended for trusted authentication code, such as an AuthenticationProvider.
Don't use it in your controller to mark an arbitrary user as authenticated. That would defeat the purpose of authentication.
What AuthenticationManager does
Now we have an unauthenticated Authentication object.
Who should verify it?
Meet AuthenticationManager.
AuthenticationManager is an interface responsible for authenticating an Authentication request.
Its most important method is:
Authentication authenticate(Authentication authentication);
Notice something interesting.
It accepts an Authentication object and returns an Authentication object.
Why?
Because the input represents an authentication request, while the returned object represents the result of the authentication process.
For example:
Input:
Username: ram
Password: r@123
Authenticated: false
After successful authentication:
Output:
Principal: UserDetails object
Credentials: Usually cleared after authentication
Authorities: ROLE_USER
Authenticated: true
The AuthenticationManager defines the authentication operation, but it doesn't necessarily implement the actual username/password verification itself.
It delegates that work to an AuthenticationProvider.
How ProviderManager delegates to AuthenticationProvider
ProviderManager is the most commonly used implementation of AuthenticationManager.
Think of AuthenticationManager as a common interface and ProviderManager as the implementation that delegates authentication requests to one or more providers.
Why do we need multiple providers?
Because an application may support different authentication mechanisms.
For example:
- Username and password.
- LDAP authentication.
- Custom authentication.
- Other authentication mechanisms supported by the application.
Instead of putting every authentication mechanism inside one giant class, Spring Security uses separate providers.
The relationship looks like this:
AuthenticationManager
|
v
ProviderManager
|
+-----------+-----------+
| | |
v v v
Provider 1 Provider 2 Provider 3
| | |
v v v
Database LDAP Custom
Login Login Login
ProviderManager checks whether a provider supports the type of Authentication object it receives.
The provider's supports() method helps determine that.
If a provider supports the request, Spring Security asks it to authenticate the request.
A provider can:
- Return an authenticated
Authenticationobject. - Return
nullwhen it cannot handle the request. - Throw an
AuthenticationExceptionwhen authentication fails.
The most important thing to remember:
AuthenticationManager delegates. AuthenticationProvider performs the actual authentication.
What DaoAuthenticationProvider does
Now let's focus on username/password authentication.
Spring Security provides a built-in implementation called DaoAuthenticationProvider.
It uses two important components:
UserDetailsServicePasswordEncoder
Its responsibility is to authenticate a username/password combination using the user information loaded by UserDetailsService.
Let's follow the process.
DaoAuthenticationProvider
|
v
UserDetailsService
|
v
Load user information
|
v
Get stored encoded password
|
v
PasswordEncoder
|
v
Compare submitted password
|
+-------+-------+
| |
v v
Match No match
| |
v v
Authentication Authentication
successful failed
For example:
Submitted password: r@123
Stored password: $2a$10$...
DaoAuthenticationProvider loads the user information and uses the configured PasswordEncoder to compare the submitted password with the stored password.
If the password is correct and the account checks pass, authentication succeeds.
If the password is incorrect, authentication fails with an authentication exception.
You don't have to implement this entire process manually. Spring Security already provides this provider.
Where UserDetailsService fits
Now we know that DaoAuthenticationProvider needs user information.
But where does it get that information?
From UserDetailsService.
UserDetailsService is an interface provided by Spring Security.
It has one main method:
UserDetails loadUserByUsername(String username);
Its job is simple:
Find the user using the supplied username and return the user's details.
For example, imagine our database contains:
+--------------------------------------+
| users |
+--------------------------------------+
| id | username | password | role |
+--------------------------------------+
| 1 | ram | $2a$... | ROLE_USER |
| 2 | kim | $2b$... | ROLE_ADMIN |
+--------------------------------------+
When someone tries to log in as ram, Spring Security calls:
userDetailsService.loadUserByUsername("ram");
The implementation retrieves the user and returns a UserDetails object.
Important: UserDetailsService does not verify the submitted password.
It only loads the user.
Password verification is handled by DaoAuthenticationProvider using PasswordEncoder.
This separation is useful because the same authentication mechanism can work with different user storage systems.
For example:
- A user stored in memory.
- A user stored in MySQL.
- A user stored in PostgreSQL.
- A user stored in MongoDB.
The provider doesn't need to know the details of your database queries. It only needs a UserDetailsService.
What happens after successful authentication
Let's say:
Username: ram
Password: r@123
The user exists, the password matches, and the account is enabled.
DaoAuthenticationProvider creates an authenticated Authentication result.
The authentication filter that initiated the authentication process then stores that result in the SecurityContextHolder.
The simplified flow is:
Authentication request
|
v
AuthenticationManager
|
v
DaoAuthenticationProvider
|
v
UserDetailsService
|
v
PasswordEncoder
|
v
Authenticated Authentication
|
v
SecurityContextHolder
What is SecurityContextHolder?
It provides access to the current security context.
The SecurityContext holds the current user's Authentication object.
For example:
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
System.out.println(authentication.getName());
If authentication succeeded and the context was populated, the output could be:
ram
This is how Spring Security makes the authenticated user's information available to the rest of the application.
We'll revisit this when we work with JWT authentication in Part 3.
Understand UserDetails and user storage
We have discussed UserDetailsService, which loads user information.
But what exactly does it return?
It returns an object implementing UserDetails.
What UserDetails contains
UserDetails is an interface that represents the user information required by Spring Security.
It provides methods such as:
String getUsername();
String getPassword();
Collection<? extends GrantedAuthority> getAuthorities();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
Let's understand why these methods exist.
Username and password
These provide the user's identity and stored password information.
Authorities
These define what the user is allowed to access.
Account status
These methods help Spring Security determine whether the account is allowed to authenticate.
For example:
Username: ram
Password: $2a$10$...
Authorities: ROLE_USER
Account non-expired: true
Account non-locked: true
Credentials non-expired: true
Enabled: true
You can implement UserDetails yourself or adapt an existing user entity to it.
The important distinction is:
UserDetailsService
|
| loads
v
UserDetails
|
| contains
v
Username + Password + Authorities + Account Status
In-memory users for learning
Spring Security provides InMemoryUserDetailsManager.
It stores user details in application memory.
This is useful when learning Spring Security or creating small demonstrations.
Example:
@Bean
public UserDetailsService userDetailsService() {
UserDetails user1 = User
.withDefaultPasswordEncoder()
.username("ram")
.password("r@123")
.roles("USER")
.build();
UserDetails user2 = User
.withDefaultPasswordEncoder()
.username("kim")
.password("k@123")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user1, user2);
}
Here we created two users.
One has the USER role and the other has the ADMIN role.
Notice this:
.roles("ADMIN")
Spring Security converts it into the authority:
ROLE_ADMIN
This is why hasRole("ADMIN") and hasAuthority("ROLE_ADMIN") are commonly used together.
One warning: User.withDefaultPasswordEncoder() is meant for samples and demos, not production password storage.
In-memory users are also not suitable for a typical production application where users register, update their profiles, and expect their accounts to remain available after the application restarts.
Database-backed users for real applications
In a real application, users are usually stored in a database.
For example, let's create a simple UserDetailsService implementation.
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() ->
new UsernameNotFoundException("User not found")
);
return org.springframework.security.core.userdetails.User
.withUsername(user.getUsername())
.password(user.getPassword())
.authorities(user.getRole())
.build();
}
}
Here:
- We receive a username.
- We search for that username in the database.
- We retrieve the user.
- We convert the user into Spring Security's
UserDetails. - We return it.
Now DaoAuthenticationProvider can use this service without knowing whether the user came from PostgreSQL, MySQL, or another storage system.
That's the benefit of using interfaces.
Your database implementation can change without requiring you to rewrite the entire authentication mechanism.
Store passwords safely
Now comes one of the most important parts of authentication.
Let's say a user registers with:
Username: ram
Password: r@123
Should we directly store this password in our database?
Absolutely not.
Let's understand why.
Why plain-text passwords are dangerous
Imagine your database stores passwords like this:
+------------------------------+
| username | password |
+------------------------------+
| ram | r@123 |
| kim | k@123 |
| john | john123 |
+------------------------------+
Suppose an attacker gets access to your database.
The attacker can immediately read every user's password.
This is a serious security problem.
Instead of storing the original password, we should store a one-way password hash.
For example:
Original password:
r@123
Stored password:
$2a$10$...
The stored value is not the original password.
During login, the application checks whether the submitted password matches the stored hash.
This is where PasswordEncoder comes in.
What NoOpPasswordEncoder does
You may have seen this line in Spring Security examples:
provider.setPasswordEncoder(
NoOpPasswordEncoder.getInstance()
);
What does it do?
The name gives us a clue.
"No Operation" means it does not perform password hashing.
For example:
PasswordEncoder encoder =
NoOpPasswordEncoder.getInstance();
String encoded = encoder.encode("r@123");
System.out.println(encoded);
System.out.println(
encoder.matches("r@123", encoded)
);
Conceptually, the output is:
r@123
true
The password is stored as it is.
There is no secure hashing involved.
Why does Spring Security provide it?
It is useful for legacy applications and simple testing scenarios where plain-text passwords are intentionally used.
But it is deprecated and explicitly documented as insecure.
Never use NoOpPasswordEncoder for a production application.
How BCryptPasswordEncoder works
Spring Security provides BCryptPasswordEncoder to hash passwords using the BCrypt algorithm.
Example:
PasswordEncoder encoder =
new BCryptPasswordEncoder();
String encodedPassword =
encoder.encode("r@123");
System.out.println(encodedPassword);
System.out.println(
encoder.matches("r@123", encodedPassword)
);
System.out.println(
encoder.matches("wrongPassword", encodedPassword)
);
The output will look similar to:
$2a$10$...
true
false
The actual encoded password will be a long BCrypt hash.
Let's understand the important difference.
When you call:
encoder.encode("r@123");
BCrypt generates a salted password hash.
A salt is random data used during password hashing.
Why do we need it?
Imagine two users choose the same password:
User 1: r@123
User 2: r@123
Without proper salting, identical passwords can produce identical stored hashes.
That makes it easier for attackers to identify users with the same password.
BCrypt uses a salt, so encoding the same password multiple times normally produces different hashes.
For example:
String hash1 = encoder.encode("r@123");
String hash2 = encoder.encode("r@123");
System.out.println(hash1.equals(hash2));
Output:
false
Does this mean the passwords are different?
No.
Both hashes represent the same original password, but they use different salts.
So how do we verify the password?
We use:
encoder.matches(rawPassword, encodedPassword);
For example:
encoder.matches("r@123", hash1);
Output:
true
Don't compare a newly generated BCrypt hash with the stored hash using equals().
Use matches() because BCrypt uses a salt.
Configure a PasswordEncoder bean
Instead of creating a password encoder wherever we need it, we can register it as a Spring bean.
A straightforward configuration using BCrypt is:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
Now Spring can inject this bean wherever a PasswordEncoder is required.
For example:
@Service
public class UserService {
private final PasswordEncoder passwordEncoder;
public UserService(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public String encodePassword(String rawPassword) {
return passwordEncoder.encode(rawPassword);
}
}
When a user registers, encode the password before saving it.
String encodedPassword =
passwordEncoder.encode(request.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
During login, DaoAuthenticationProvider uses the configured password encoder to verify the submitted password against the stored encoded password.
Important: Registration and login must use compatible password-encoding strategies. If you store a BCrypt hash, configure authentication to verify it using BCrypt-compatible matching.
There is another option worth knowing: DelegatingPasswordEncoder.
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories
.createDelegatingPasswordEncoder();
}
Why should we consider it?
It supports multiple password formats and identifies the encoder using a prefix in the stored password.
For example:
{bcrypt}$2a$10$...
The {bcrypt} prefix tells Spring Security which encoder should be used to verify the password.
This is useful when an application needs to support password migration or different password formats over time.
For many applications, DelegatingPasswordEncoder is a good default choice.
BCrypt strength and password migration
You may have noticed this:
new BCryptPasswordEncoder(10);
What does 10 mean?
It is the BCrypt strength, also called the work factor.
BCrypt deliberately makes password hashing computationally expensive.
A higher strength increases the work required to calculate the hash and verify a password.
Why make it slow?
Because attackers may try millions of password combinations.
Making each password verification more expensive makes large-scale password guessing more difficult.
But there is a trade-off.
If the work factor is too high, legitimate users may experience slow login requests, and your server may consume too many resources.
Spring Security's BCrypt default strength is 10.
You should benchmark the cost on your actual production hardware and tune it according to your application's security and performance requirements.
One more thing about migration.
Suppose your old application stored plain-text passwords, and now you want to move to BCrypt.
You cannot simply switch the encoder and expect old plain-text values to match BCrypt hashes.
You need a migration strategy.
DelegatingPasswordEncoder can help applications support multiple formats during migration. You can also use a password-reset process to move users to a new secure password format.
Connect AuthenticationManager to your application
So far, we have understood the individual components.
Now let's see how our own application can use them.
Imagine we have created a REST endpoint:
POST /users/login
The client sends a username and password.
We want Spring Security to authenticate those credentials.
For this, we can inject AuthenticationManager into our service or controller.
Expose AuthenticationManager as a bean
Spring Security provides AuthenticationConfiguration, which can give us the configured AuthenticationManager.
We can expose it as a bean:
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration configuration
) throws Exception {
return configuration.getAuthenticationManager();
}
Now we can inject AuthenticationManager into another Spring-managed component.
For example:
@Service
public class LoginService {
private final AuthenticationManager authenticationManager;
public LoginService(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
}
Why do we need this?
Because our custom login logic can now delegate credential verification to Spring Security instead of manually checking passwords.
Authenticate credentials in a login service
Let's see the actual authentication call.
@Service
public class LoginService {
private final AuthenticationManager authenticationManager;
public LoginService(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public Authentication login(String username, String password) {
Authentication authenticationRequest =
new UsernamePasswordAuthenticationToken(
username,
password
);
return authenticationManager.authenticate(
authenticationRequest
);
}
}
Let's understand what happens here.
First:
new UsernamePasswordAuthenticationToken(
username,
password
);
We create an unauthenticated authentication request.
Then:
authenticationManager.authenticate(authenticationRequest);
We pass the request to Spring Security.
The configured authentication manager delegates the request to a suitable provider.
The provider loads the user, verifies the password, and returns an authenticated result if everything is valid.
If authentication fails, Spring Security throws an AuthenticationException.
In a real REST API, you should handle that exception and return an appropriate HTTP response without exposing sensitive information.
Why a custom login endpoint is different from form login
This is an important distinction.
In your configuration, you have:
.formLogin(Customizer.withDefaults())
This enables Spring Security's form-login support.
Spring Security provides filters that handle form-login requests and delegate authentication to the configured authentication manager.
But imagine you create your own REST endpoint:
POST /users/login
And the request body is JSON:
{
"username": "ram",
"password": "r@123"
}
The form-login filter does not automatically know how to process your custom JSON request body.
Your controller or service must explicitly invoke the AuthenticationManager, or you must implement an appropriate custom authentication filter.
This is why exposing an AuthenticationManager bean is useful for a custom REST login flow.
We'll use this idea in Part 3 when we connect login authentication with JWT generation.
Connect the flow to your SecurityConfig
Now let's revisit the code you shared.
You already have an AuthenticationProvider bean and an AuthenticationManager bean.
Let's understand what each part does.
Read your AuthenticationProvider bean
Your code:
@Bean
public AuthenticationProvider authenticationProvider(
UserDetailsService userDetailsService
) {
DaoAuthenticationProvider provider =
new DaoAuthenticationProvider(userDetailsService);
provider.setPasswordEncoder(
new BCryptPasswordEncoder(10)
);
return provider;
}
Let's break it down.
Step 1: Receive UserDetailsService
UserDetailsService userDetailsService
Spring injects your UserDetailsService implementation.
In your project, this could be MyUserDetailsService.
Its job is to load the user from your database.
Step 2: Create DaoAuthenticationProvider
DaoAuthenticationProvider provider =
new DaoAuthenticationProvider(userDetailsService);
We create a provider that uses the supplied UserDetailsService.
This provider knows how to authenticate username/password requests using the loaded user details.
Step 3: Configure PasswordEncoder
provider.setPasswordEncoder(
new BCryptPasswordEncoder(10)
);
We tell the provider how to verify passwords.
If the database contains BCrypt hashes, the provider can use BCrypt to compare the submitted password with the stored hash.
Step 4: Return the provider
return provider;
We register the provider as a Spring bean.
Spring Security can use this provider as part of its authentication configuration.
Follow a login request from start to finish
Let's put everything together.
Assume:
- The user is stored in your database.
- Your
MyUserDetailsServiceimplementsUserDetailsService. - The stored password is a BCrypt hash.
- Your
DaoAuthenticationProviderusesBCryptPasswordEncoder.
The authentication process looks like this:
Login Request
|
v
Username: ram, Password: r@123
|
v
Unauthenticated Authentication
|
v
AuthenticationManager
|
v
ProviderManager
|
v
DaoAuthenticationProvider
|
v
MyUserDetailsService
|
v
Load user from database
|
v
UserDetails object
|
v
BCryptPasswordEncoder
|
v
Compare submitted password
|
+------+------+
| |
v v
Password Password
matches incorrect
| |
v v
Authenticated Authentication
Authentication failed
|
v
SecurityContext
Now the entire purpose of each component should be clearer.
Common issues in your current configuration
Let's look at a few things in your code that are worth checking.
1. Your UserDetailsService must be registered
Your provider expects a UserDetailsService.
Make sure you have an implementation registered as a Spring bean.
For example:
@Service
public class MyUserDetailsService implements UserDetailsService {
// loadUserByUsername implementation
}
Otherwise, Spring won't have a service to inject into your provider.
2. Registration must encode the password
If your login provider uses BCrypt, make sure your registration logic stores an encoded password.
For example:
user.setPassword(
passwordEncoder.encode(request.getPassword())
);
If you store the raw password but configure BCrypt, authentication will fail.
3. Keep password encoding consistent
You currently configure:
new BCryptPasswordEncoder(10)
This is fine when the stored passwords are BCrypt hashes compatible with that encoder.
If you later switch to DelegatingPasswordEncoder, make sure existing stored hashes have the expected {bcrypt} prefix or are migrated appropriately.
4. Don't mix up form login and custom JSON login
Your configuration enables:
.formLogin(Customizer.withDefaults())
That does not automatically turn /users/login into a JSON login endpoint.
If you want a custom REST login endpoint, invoke the AuthenticationManager from your login flow.
5. Don't use NoOpPasswordEncoder in production
You have this commented-out code:
provider.setPasswordEncoder(
NoOpPasswordEncoder.getInstance()
);
Keep it disabled.
Use a secure password encoder such as BCrypt or the default delegating encoder.
6. Check your role and authority values
If you create users using:
.roles("ADMIN")
Spring Security creates the authority:
ROLE_ADMIN
So remember the difference between:
.hasRole("ADMIN")
and:
.hasAuthority("ROLE_ADMIN")
They are related, but they don't take exactly the same input.
Which one should I use?
Let's quickly connect the components to their responsibilities.
- Authentication: Represents the authentication request or authenticated user.
- UsernamePasswordAuthenticationToken: Carries username/password credentials during username/password authentication.
- AuthenticationManager: Provides the authentication operation.
-
ProviderManager: Common
AuthenticationManagerimplementation that delegates to providers. - AuthenticationProvider: Performs a particular authentication mechanism.
-
DaoAuthenticationProvider: Authenticates username/password using
UserDetailsServiceandPasswordEncoder. - UserDetailsService: Loads user information.
- UserDetails: Represents the user information required by Spring Security.
- PasswordEncoder: Encodes passwords and verifies submitted passwords.
- BCryptPasswordEncoder: Provides BCrypt-based password hashing.
- DelegatingPasswordEncoder: Supports multiple password formats and password-encoding migration.
For a typical username/password application backed by a database, this is a good starting point:
AuthenticationManager
|
v
DaoAuthenticationProvider
|
+----------------------+
| |
v v
UserDetailsService PasswordEncoder
|
v
Database
You generally don't need to write your own AuthenticationProvider just to authenticate users against a database. DaoAuthenticationProvider already handles that use case.
Common mistakes
Confusing AuthenticationManager with AuthenticationProvider:
AuthenticationManagerprovides the authentication operation, whileAuthenticationProviderperforms a specific authentication mechanism. Understand the delegation instead of treating them as the same component.Assuming UserDetailsService verifies passwords: It only loads user information. Password verification is handled by the authentication provider using a
PasswordEncoder.Storing raw passwords in the database: Never store plain-text passwords in a production application. Encode passwords using a suitable password encoder before saving them.
Comparing BCrypt hashes using equals(): BCrypt uses a salt, so encoding the same password twice can produce different hashes. Use
passwordEncoder.matches(rawPassword, encodedPassword).Using NoOpPasswordEncoder in production: It does not hash passwords and is deprecated as insecure. Use BCrypt or
DelegatingPasswordEncoderinstead.Assuming a custom JSON login endpoint is handled by formLogin(): Form login and your custom JSON login endpoint are different flows. Invoke
AuthenticationManagerfrom your custom login logic or implement an appropriate authentication filter.
Quick recap
- Authentication is the process of verifying a user's identity.
-
Authenticationrepresents an authentication request or an authenticated user. -
UsernamePasswordAuthenticationTokencarries username/password authentication information. -
AuthenticationManagerdelegates authentication to suitable providers. -
ProviderManageris the common implementation ofAuthenticationManager. -
DaoAuthenticationProviderauthenticates users usingUserDetailsServiceandPasswordEncoder. -
UserDetailsServiceloads user information. -
UserDetailscontains the username, password, authorities, and account status. -
PasswordEncoderhandles password encoding and verification. -
NoOpPasswordEncoderis insecure and should not be used in production. -
BCryptPasswordEncoderprovides adaptive one-way password hashing. -
DelegatingPasswordEncodersupports multiple password formats and migration. - A custom REST login endpoint can use
AuthenticationManagerto authenticate credentials.
Try it yourself
Don't just read these concepts. Try implementing them.
Practice 1: Understand Authentication
Create a UsernamePasswordAuthenticationToken using a username and password.
Print:
- Principal
- Credentials
isAuthenticated()
Then create an authenticated token using a UserDetails object and authorities. Compare the results.
Practice 2: Configure BCrypt
Create a PasswordEncoder bean using BCryptPasswordEncoder.
Encode the same password twice.
Check whether both hashes are equal.
Then use matches() to verify the original password against both hashes.
Practice 3: Understand DaoAuthenticationProvider
Create a database-backed UserDetailsService.
Configure DaoAuthenticationProvider with that service and a PasswordEncoder.
Try logging in with:
- A valid username and password.
- A valid username and incorrect password.
- An invalid username.
Observe what happens in each case.
Bonus challenge
Create a custom /users/login REST endpoint.
Inject AuthenticationManager into your service and authenticate the submitted username and password.
Don't manually compare passwords inside the controller. Let Spring Security handle authentication.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)