UserDetailsService in Spring Security
UserDetailsService is the interface Spring Security calls when it needs to find a user by username. It does not check passwords and it does not decide access. It has exactly one job: given a username, return that user's stored password hash, authorities and account status, or report that no such user exists.
Because this lookup is separated from everything else, you can move users from memory to a database, or from one table design to another, without touching login filters or password checks. This tutorial explains the interface and the UserDetails object it returns, then loads delivery riders from a database using the built-in JdbcUserDetailsManager.
1. What Is UserDetailsService?
The interface has one method:
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
It returns a UserDetails, a read-only view of a user that Spring Security understands. If the username is unknown, it must throw UsernameNotFoundException; returning null breaks the contract.
UserDetails exposes seven methods. Three are always needed and four describe the account status. In Spring Security 6.3 and later, the four status methods have default implementations that return true, so a simple implementation only has to supply the first three.
| Method | Meaning | If false or invalid |
|---|---|---|
getUsername() | The login name | - |
getPassword() | The stored password hash, such as {bcrypt}$2a$10$... | Password check fails |
getAuthorities() | Roles and permissions, for example ROLE_RIDER | User has no access rights |
isEnabled() | Account is active | DisabledException |
isAccountNonLocked() | Account is not locked, for example after failed logins | LockedException |
isAccountNonExpired() | Account is still valid | AccountExpiredException |
isCredentialsNonExpired() | Password does not need changing | CredentialsExpiredException |
2. Why UserDetailsService Is Needed
Login filters and the authentication provider should not care where users live. Without a common lookup interface, every storage option would need its own login code. With it, the same DaoAuthenticationProvider works for an in-memory list in a demo, a JDBC table in a small app and an LDAP directory or JPA entity in a large one.
The account-status flags matter as much as the password. They let operations staff disable a departed employee, lock an account after suspicious activity or force a password change, all without deleting data.
3. How UserDetailsService Is Used During Login
DaoAuthenticationProvidercallsloadUserByUsernamewith the submitted username.- If the user is unknown,
UsernameNotFoundExceptionis thrown. The provider converts it intoBadCredentialsExceptionby default, so the client cannot tell an unknown user from a wrong password. - Before the password check, the provider checks
isAccountNonLocked,isEnabledandisAccountNonExpired. After a successful password check, it checksisCredentialsNonExpired. - The submitted password is compared with the stored hash through the
PasswordEncoder. On success, the user's authorities are copied into the authenticated token.
4. Built-in Implementations
| Class | Stores users in | Good for |
|---|---|---|
InMemoryUserDetailsManager | A map in memory | Demos, tests, tiny internal tools |
JdbcUserDetailsManager | SQL tables via JDBC (a default schema is provided) | Simple database-backed apps |
LdapUserDetailsManager | An LDAP directory | Corporate directories |
| Your own class | Anything: JPA entities, a REST service, a legacy system | Most real applications; see custom UserDetailsService |
The classes ending in Manager implement UserDetailsManager, which adds createUser, updateUser, deleteUser, changePassword and userExists to the read-only lookup.
5. A Complete Example: Delivery Riders in a Database
A food delivery company keeps its riders in a database. Active riders can see their shifts, while riders who have left are disabled rather than deleted, so their delivery history stays intact. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2, an in-memory H2 database and the default schema shipped inside Spring Security.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
package com.javabytechie.riders;
import javax.sql.DataSource;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().hasRole("RIDER"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
JdbcUserDetailsManager userDetailsService(DataSource dataSource) {
return new JdbcUserDetailsManager(dataSource);
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
// Demo data: in production, riders are created by an onboarding process
@Bean
ApplicationRunner seedRiders(JdbcUserDetailsManager riders, PasswordEncoder encoder) {
return args -> {
riders.createUser(User.withUsername("arjun")
.password(encoder.encode("arjun-pass")).roles("RIDER").build());
riders.createUser(User.withUsername("bela")
.password(encoder.encode("bela-pass")).roles("RIDER")
.disabled(true) // left the company
.build());
};
}
}
package com.javabytechie.riders;
import java.security.Principal;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ShiftController {
@GetMapping("/api/shifts")
public List<String> shifts(Principal principal) {
return List.of(principal.getName() + ": Sat 18:00-22:00, HSR Layout zone");
}
}
package com.javabytechie.riders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RiderPortalApplication {
public static void main(String[] args) {
SpringApplication.run(RiderPortalApplication.class, args);
}
}
spring:
sql:
init:
# Default users and authorities tables shipped with Spring Security (H2 syntax)
schema-locations: classpath:org/springframework/security/core/userdetails/jdbc/users.ddl
logging:
level:
# Shows why a login failed; useful while learning, too verbose for production
org.springframework.security.web.authentication.www: DEBUG
6. Step-by-Step Code Explanation
- The schema.
users.ddlcreates auserstable (username, password, enabled) and anauthoritiestable. Spring Boot runs it at startup throughspring.sql.init.schema-locations. The file uses H2 syntax; for MySQL or PostgreSQL, copy it and adjust the column types. - The bean. Declaring a
JdbcUserDetailsManagerbean is enough: Spring Security finds the singleUserDetailsServicebean and builds aDaoAuthenticationProvideraround it. Spring Boot's generated default user disappears at the same time. - Seeding users.
createUserinserts rows into both tables. The password goes throughencoder.encode, so the database stores a{bcrypt}hash, never the plain password. - Disabling an account.
disabled(true)setsenabled = false. Bela's password is still correct, but the provider rejects her before the password is checked.
7. Expected Output
Requests from an active rider, a disabled rider, a wrong password and an unknown user:
$ curl -u arjun:arjun-pass localhost:8080/api/shifts
HTTP/1.1 200
["arjun: Sat 18:00-22:00, HSR Layout zone"]
$ curl -u bela:bela-pass localhost:8080/api/shifts
HTTP/1.1 401
{"timestamp":"2026-11-18T12:15:15.257Z","status":401,"error":"Unauthorized","path":"/api/shifts"}
$ curl -u arjun:wrong-pass localhost:8080/api/shifts
HTTP/1.1 401
{"timestamp":"2026-11-18T12:15:15.330Z","status":401,"error":"Unauthorized","path":"/api/shifts"}
$ curl -u nobody:any-pass localhost:8080/api/shifts
HTTP/1.1 401
{"timestamp":"2026-11-18T12:15:15.397Z","status":401,"error":"Unauthorized","path":"/api/shifts"}
All three failures return the same 401, which is deliberate: an attacker learns nothing about which accounts exist or which are disabled. With the DEBUG logging from application.yml, BasicAuthenticationFilter logs "Failed to process authentication request" followed by the exception. These are the three exceptions, in the order of the failed requests above:
DisabledException: User is disabled
BadCredentialsException: Bad credentials
BadCredentialsException: Bad credentials
Note that the unknown user is logged as Bad credentials, exactly like the wrong password. DaoAuthenticationProvider hides UsernameNotFoundException on purpose.
8. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Separates user storage from authentication logic | Only supports lookup by a single username string |
| Built-in managers cover memory, JDBC and LDAP | The default JDBC schema is minimal: no locked or expired columns |
| Account status flags give operational control without deleting users | Status flags must be kept in sync with your real user lifecycle |
| Works unchanged with form login, HTTP Basic and remember-me | Not used for JWT or OAuth2 logins, which take identity from the token |
9. Common Mistakes and Best Practices
- Returning
nullfor an unknown user. ThrowUsernameNotFoundExceptioninstead. - Storing plain-text passwords in the table. Always store the output of
PasswordEncoder.encode. - Leaking account state in error messages. Keep the client response generic and put the reason in the server log, as above.
- Declaring two
UserDetailsServicebeans. Spring Security cannot pick one automatically. Keep a single bean or build the provider yourself. - Loading too much in
loadUserByUsername. It runs on every login (and on every request for HTTP Basic). Load only what authentication needs.
10. Summary
UserDetailsService.loadUserByUsernamefinds a user and returnsUserDetails, or throwsUsernameNotFoundException.UserDetailscarries the password hash, authorities and four account-status flags.DaoAuthenticationProvidercalls the service, checks status flags, then verifies the password.JdbcUserDetailsManagerwith the bundledusers.ddlgives database-backed users with almost no code.- Unknown users, wrong passwords and disabled accounts all look identical to the client.
11. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between UserDetails and UserDetailsService?
UserDetails is the data: username, password hash, authorities and status flags. UserDetailsService is the lookup that finds that data by username.
Q2. Does UserDetailsService check the password?
No. It only loads the user. DaoAuthenticationProvider compares the submitted password with the stored hash using a PasswordEncoder.
Q3. What should loadUserByUsername do when the user does not exist?
Throw UsernameNotFoundException. DaoAuthenticationProvider then reports BadCredentialsException so the client cannot discover which usernames exist.
Q4. What is the difference between UserDetailsService and UserDetailsManager?
UserDetailsManager extends UserDetailsService with methods to create, update and delete users and change passwords. InMemoryUserDetailsManager and JdbcUserDetailsManager implement it.
Q5. How do I disable a user without deleting them?
Return false from isEnabled(), for example by setting the enabled column to false with JdbcUserDetailsManager. Login attempts then fail with DisabledException.