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 AuthenticationManager to authenticate users.

  • Returns a UserDetails object if the user exists.

  • Throws UsernameNotFoundException if 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.

  • InMemoryUserDetailsManager manages 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 UsernameNotFoundException if the user does not exist.

  • Returns a UserDetails object that Spring Security can use.

How Spring Security Uses UserDetailsService in AuthenticationManager

Spring Security’s AuthenticationManager uses UserDetailsService to load user details.

  • UserDetailsService fetches user information.

  • DaoAuthenticationProvider validates the user credentials.

  • PasswordEncoder compares the stored and provided passwords.

Configuration for UserDetailsService

Spring Boot 2 (WebSecurityConfigurerAdapter)

  • Uses WebSecurityConfigurerAdapter (Deprecated in Spring Security 5.7+).

  • Uses AuthenticationManagerBuilder to register UserDetailsService.

Spring Boot 3 (Bean-based Security Configuration)

  • Uses @Bean configuration instead of WebSecurityConfigurerAdapter.

  • Defines UserDetailsService explicitly as a Spring Bean.

  • Uses SecurityFilterChain for security rules.

Last updated