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
- What does Authentication represent?
- Principal, credentials and authorities
- Follow the authentication flow
- Create an unauthenticated Authentication object
- What AuthenticationManager does
- How ProviderManager delegates to AuthenticationProvider
- What DaoAuthenticationProvider does
- Where UserDetailsService fits
- What happens after successful authentication
- Understand UserDetails and user storage
- What UserDetails contains
- In-memory users for learning
- Database-backed users for real applications
- Store passwords safely
- Why plain-text passwords are dangerous
- What NoOpPasswordEncoder does
- How BCryptPasswordEncoder works
- Configure a PasswordEncoder bean
- BCrypt strength and password migration
- Connect AuthenticationManager to your application
- Expose AuthenticationManager as a bean
- Authenticate credentials in a login service
- Why a custom login endpoint is different from form login
- Connect the flow to your SecurityConfig
- Read your AuthenticationProvider bean
- Follow a login request from start to finish
- Common issues in your current configuration
- 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 publicSource:https://dev.to/mayur_bodhare/spring-security-part-2-authenticationmanager-and-bcrypt-2kn4Related posts
I Built an Education App: Here’s What I Learned About Scalability
Travel Agency Booking Portals: Building Scalable B2B/B2C Platforms for the Modern Traveler
Retail ERP & POS Software: Why Off-the-Shelf Solutions Fail Growing Businesses in MENA
