UserDetailsService
About
UserDetailsService is a core interface in Spring Security responsible for retrieving user details during authentication. It loads user-specific data from a database, in-memory store, or external system and returns a UserDetails object, which Spring Security then uses for authentication and authorization.
Spring Security's authentication system heavily depends on UserDetailsService to verify users and check roles, passwords, and account status.
Responsibilities of UserDetailsService
Loads user details (username, password, roles) from a persistent store.
Used by
AuthenticationManagerto authenticate users.Returns a
UserDetailsobject if the user exists.Throws
UsernameNotFoundExceptionif the user is not found.Can be customized to fetch additional user attributes.
UserDetailsService Interface
Spring Security provides a interface:
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}Method
Purpose
loadUserByUsername(String username)
Fetches user details based on username.
Throws UsernameNotFoundException
If no user is found with the given username.
Default Implementation: In-Memory UserDetailsService
Spring Security provides a default InMemoryUserDetailsManager that loads users from memory.
Stores users in-memory (not recommended for production).
Uses BCrypt for password encoding.
InMemoryUserDetailsManagermanages users in memory.
Custom Implementation: Database-backed UserDetailsService
For real-world applications, we fetch users from a database using JPA, JDBC, or an external API.
1. Create a User Entity
2. Create User Repository
Queries the database to find users by username.
3. Implement Custom UserDetailsService
Retrieves user details from the database.
Throws
UsernameNotFoundExceptionif the user does not exist.Returns a
UserDetailsobject that Spring Security can use.
How Spring Security Uses UserDetailsService in AuthenticationManager
Spring Security’s AuthenticationManager uses UserDetailsService to load user details.
UserDetailsServicefetches user information.DaoAuthenticationProvidervalidates the user credentials.PasswordEncodercompares the stored and provided passwords.
Configuration for UserDetailsService
Spring Boot 2 (WebSecurityConfigurerAdapter)
WebSecurityConfigurerAdapter)Uses
WebSecurityConfigurerAdapter(Deprecated in Spring Security 5.7+).Uses
AuthenticationManagerBuilderto registerUserDetailsService.
Spring Boot 3 (Bean-based Security Configuration)
Uses
@Beanconfiguration instead ofWebSecurityConfigurerAdapter.Defines
UserDetailsServiceexplicitly as a Spring Bean.Uses
SecurityFilterChainfor security rules.
Last updated