Definition
- UserDetailsService – a functional interface with one method,
loadUserByUsername(String), that returns a UserDetails object or throws UsernameNotFoundException. - UserDetails – an interface representing the user's identity: username, password hash, granted authorities, and four boolean flags (account expired, locked, credentials expired, enabled).
- DaoAuthenticationProvider – calls UserDetailsService to load user details, then uses PasswordEncoder to verify the password; UserDetailsService does NOT verify passwords.
- InMemoryUserDetailsManager – a test/demo implementation that stores users in memory; never appropriate for production.
- JdbcUserDetailsManager – a JDBC-based implementation that loads users from a standard database schema.
UserDetailsService is like a bank's customer records clerk. When a customer walks in and says "I am Priya, account SAV2001," the clerk (UserDetailsService) looks up Priya's file in the records room (database). The file contains her photo, signature specimen (password hash), and access level (authorities). The clerk hands the file to the security officer (DaoAuthenticationProvider), who compares the customer's actual signature with the specimen. The clerk only retrieves the file; the security officer makes the authentication decision.
Understanding the Concepts
What is UserDetailsService?
UserDetailsService is a core interface in Spring Security for loading user-specific data. It has one method:
public interface UserDetailsService {
UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException;
}
This method loads user data from any source: a relational database, an in-memory store, an LDAP directory, or an external API. It returns a UserDetails object or throws UsernameNotFoundException if the user does not exist.
What does UserDetails contain?
UserDetails is an interface with these methods:
| Method | Returns | Purpose |
|---|---|---|
getUsername() | String | The username used for authentication |
getPassword() | String | The stored password hash (BCrypt, Argon2, etc.) |
getAuthorities() | Collection | Roles and permissions (ROLE_ADMIN, ACCOUNT_READ, etc.) |
isAccountNonExpired() | boolean | True if the account has not expired |
isAccountNonLocked() | boolean | True if the account is not locked |
isCredentialsNonExpired() | boolean | True if the password has not expired |
isEnabled() | boolean | True if the account is active |
Spring Security's User class is a built-in implementation of UserDetails that you can create with a builder:
UserDetails user = User.builder()
.username("rajesh")
.password(passwordEncoder.encode("secure-password"))
.roles("TELLER", "AUDITOR")
.accountLocked(false)
.disabled(false)
.build();
How do you implement UserDetailsService for a banking application?
In production, you load users from your database:
package com.bank.service;
import com.bank.model.BankEmployee;
import com.bank.repository.BankEmployeeRepository;
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.stream.Collectors;
@Service
public class BankEmployeeDetailsService implements UserDetailsService {
private final BankEmployeeRepository employeeRepository;
public BankEmployeeDetailsService(BankEmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
@Override
public UserDetails loadUserByUsername(String employeeId) {
BankEmployee employee = employeeRepository
.findByEmployeeId(employeeId)
.orElseThrow(() -> new UsernameNotFoundException(
"Employee not found: " + employeeId
));
return User.builder()
.username(employee.getEmployeeId())
.password(employee.getPasswordHash())
.authorities(employee.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toList()))
.accountExpired(employee.getAccountExpiry() != null
&& employee.getAccountExpiry().isBefore(java.time.LocalDate.now()))
.accountLocked(employee.isLocked())
.credentialsExpired(employee.isPasswordExpired())
.disabled(!employee.isActive())
.build();
}
}
The entity class:
package com.bank.model;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.util.Set;
@Entity
@Table(name = "bank_employees")
public class BankEmployee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String employeeId;
@Column(nullable = false)
private String passwordHash;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "employee_roles",
joinColumns = @JoinColumn(name = "employee_id"))
@Column(name = "role")
private Set<String> roles;
private boolean active;
private boolean locked;
private boolean passwordExpired;
private LocalDate accountExpiry;
// Getters and setters
public String getEmployeeId() { return employeeId; }
public String getPasswordHash() { return passwordHash; }
public Set<String> getRoles() { return roles; }
public boolean isActive() { return active; }
public boolean isLocked() { return locked; }
public boolean isPasswordExpired() { return passwordExpired; }
public LocalDate getAccountExpiry() { return accountExpiry; }
}
What is the difference between UserDetailsService and AuthenticationProvider?
| Aspect | UserDetailsService | AuthenticationProvider |
|---|---|---|
| Purpose | Loads user data from a store | Performs the full authentication |
| Verifies password | No | Yes (via PasswordEncoder) |
| Interface method | loadUserByUsername(String) | authenticate(Authentication) + supports(Class) |
| When to implement | Standard username/password flow | Non-standard auth (OTP, API key, hardware token) |
| Used by | DaoAuthenticationProvider | ProviderManager |
For most banking applications, implementing UserDetailsService is sufficient. DaoAuthenticationProvider handles password verification automatically.
When should you use InMemoryUserDetailsManager?
Only for demos, prototypes, and integration tests. Never for production.
// Demo/test only: in-memory user store
@Bean
UserDetailsService userDetailsService(PasswordEncoder encoder) {
UserDetails teller = User.builder()
.username("rajesh")
.password(encoder.encode("demo-password"))
.roles("TELLER")
.build();
UserDetails admin = User.builder()
.username("pankaj")
.password(encoder.encode("admin-password"))
.roles("ADMIN", "TELLER")
.build();
return new InMemoryUserDetailsManager(teller, admin);
}
- Production issues with InMemoryUserDetailsManager:
- Users are lost when the application restarts.
- No support for password changes or account locking.
- Does not scale to thousands of users.
- No audit trail for user management operations.
What are common mistakes?
Returning null instead of throwing UsernameNotFoundException:
// WRONG: Returning null causes a NullPointerException
// deep inside DaoAuthenticationProvider
@Override
public UserDetails loadUserByUsername(String username) {
BankEmployee emp = repository.findByEmployeeId(username)
.orElse(null); // WRONG
if (emp == null) return null; // WRONG
// ...
}
// CORRECT: Throw UsernameNotFoundException
@Override
public UserDetails loadUserByUsername(String username) {
return repository.findByEmployeeId(username)
.map(this::toUserDetails)
.orElseThrow(() -> new UsernameNotFoundException(
"Employee not found: " + username
));
}
Another mistake is returning the raw password instead of the hash:
// WRONG: Storing and returning plain text password
.password(employee.getPlainPassword()) // NEVER do this
// CORRECT: The database stores only the BCrypt hash
.password(employee.getPasswordHash()) // BCrypt hash like $2a$12$...
What about the account status flags?
DaoAuthenticationProvider checks all four status flags before returning a successful authentication. If any flag indicates a problem, authentication fails with a specific exception:
| Flag | Exception thrown if false |
|---|---|
isAccountNonExpired() | AccountExpiredException |
isAccountNonLocked() | LockedException |
isCredentialsNonExpired() | CredentialsExpiredException |
isEnabled() | DisabledException |
- In a banking application, these flags map to real business rules:
- Account expired: employee contract ended.
- Account locked: too many failed login attempts or compliance hold.
- Credentials expired: password must be changed every 90 days (RBI compliance).
- Disabled: employee resigned or was terminated.
What should a senior engineer know?
- UserDetailsService is called once per authentication, not once per request. After authentication, the resulting Authentication object is stored in SecurityContextHolder.
- For performance, consider caching UserDetailsService calls if the database is slow. But invalidate the cache when user roles or status change.
- DaoAuthenticationProvider pre-checks and post-checks are separate. Pre-checks verify account status flags. Post-checks verify the password. This order means a locked account is rejected before the password is even checked.
- In a multi-tenant banking application, include the tenant ID in the username lookup (e.g., "HDFC:rajesh") or use a custom AuthenticationProvider that handles tenant resolution.
Visual Overview
┌──────────────────────────────────────────┐
│ DaoAuthenticationProvider │
│ authenticate(token) │
└──────────────────┬───────────────────────┘
│
┌─────────┴──────────┐
▼ │
┌──────────────────┐ │
│ UserDetailsService│ │
│ loadUserByUsername│ │
│ ("rajesh") │ │
└────────┬─────────┘ │
│ │
▼ │
┌──────────────────┐ │
│ Pre-checks: │ │
│ isAccountNon │ │
│ Expired? YES │ │
│ isAccountNon │ │
│ Locked? YES │ │
│ isEnabled? YES │ │
└────────┬─────────┘ │
│ │
▼ │
┌──────────────────┐ │
│ PasswordEncoder │ │
│ matches(raw, │ │
│ storedHash) │ │
│ = true │ │
└────────┬─────────┘ │
│ │
▼ │
┌──────────────────┐ │
│ Post-checks: │ │
│ isCredentialsNon │ │
│ Expired? YES │ │
└────────┬─────────┘ │
│ │
▼ ▼
┌──────────────────────────────────────────┐
│ Return authenticated token │
│ (principal + authorities) │
└──────────────────────────────────────────┘
Key Takeaway
UserDetailsService is the bridge between your database and Spring Security's authentication mechanism. Its sole responsibility is to look up a user by username and return a UserDetails object containing the stored password hash, authorities, and account status flags.
In a banking application, Rajesh implements BankEmployeeDetailsService that queries the bank_employees table, maps the entity to Spring Security's User builder, and returns it with the correct roles (TELLER, AUDITOR, ADMIN) and status flags (locked, expired, disabled). DaoAuthenticationProvider then handles the password verification using the configured PasswordEncoder.
The separation of concerns is deliberate. UserDetailsService only loads data. DaoAuthenticationProvider only verifies credentials. PasswordEncoder only handles hashing. Each component has one job, making the system easier to test and maintain. If Priya's account is locked after three failed login attempts, the locked flag in the database is reflected in the UserDetails, and DaoAuthenticationProvider rejects the authentication before even checking the password.
The most common mistake is returning null from loadUserByUsername instead of throwing UsernameNotFoundException. The second most common mistake is storing or comparing plain text passwords. Both are critical security violations in a banking context.
The one sentence to remember: UserDetailsService loads user data from the database, DaoAuthenticationProvider verifies the password, and together they handle standard username/password authentication in Spring Security.
---