00:00

UserDetailsService in Spring Security

Last updated:

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:

UserDetailsService.java
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.

MethodMeaningIf 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_RIDERUser has no access rights
isEnabled()Account is activeDisabledException
isAccountNonLocked()Account is not locked, for example after failed loginsLockedException
isAccountNonExpired()Account is still validAccountExpiredException
isCredentialsNonExpired()Password does not need changingCredentialsExpiredException

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

DaoAuthenticationProvider calling UserDetailsServiceDaoAuthenticationProvider calls loadUserByUsername, receives UserDetails, checks the account status flags, then compares the submitted password with the stored hash using PasswordEncoder. DaoAuthentication Provider UserDetailsService loadUserByUsername("arjun") Account status checks enabled, locked, expired PasswordEncoder matches(raw, storedHash) users and authorities tables (or memory, LDAP) query
Figure 1: the provider loads the user, checks status, then checks the password; the lookup never sees the submitted password.
  1. DaoAuthenticationProvider calls loadUserByUsername with the submitted username.
  2. If the user is unknown, UsernameNotFoundException is thrown. The provider converts it into BadCredentialsException by default, so the client cannot tell an unknown user from a wrong password.
  3. Before the password check, the provider checks isAccountNonLocked, isEnabled and isAccountNonExpired. After a successful password check, it checks isCredentialsNonExpired.
  4. 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

ClassStores users inGood for
InMemoryUserDetailsManagerA map in memoryDemos, tests, tiny internal tools
JdbcUserDetailsManagerSQL tables via JDBC (a default schema is provided)Simple database-backed apps
LdapUserDetailsManagerAn LDAP directoryCorporate directories
Your own classAnything: JPA entities, a REST service, a legacy systemMost 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.

pom.xml (dependencies)
<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());
        };
    }
}

6. Step-by-Step Code Explanation

  1. The schema. users.ddl creates a users table (username, password, enabled) and an authorities table. Spring Boot runs it at startup through spring.sql.init.schema-locations. The file uses H2 syntax; for MySQL or PostgreSQL, copy it and adjust the column types.
  2. The bean. Declaring a JdbcUserDetailsManager bean is enough: Spring Security finds the single UserDetailsService bean and builds a DaoAuthenticationProvider around it. Spring Boot's generated default user disappears at the same time.
  3. Seeding users. createUser inserts rows into both tables. The password goes through encoder.encode, so the database stores a {bcrypt} hash, never the plain password.
  4. Disabling an account. disabled(true) sets enabled = 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:

Terminal
$ 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:

Terminal
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

AdvantagesLimitations
Separates user storage from authentication logicOnly supports lookup by a single username string
Built-in managers cover memory, JDBC and LDAPThe default JDBC schema is minimal: no locked or expired columns
Account status flags give operational control without deleting usersStatus flags must be kept in sync with your real user lifecycle
Works unchanged with form login, HTTP Basic and remember-meNot used for JWT or OAuth2 logins, which take identity from the token

9. Common Mistakes and Best Practices

  • Returning null for an unknown user. Throw UsernameNotFoundException instead.
  • 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 UserDetailsService beans. 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.loadUserByUsername finds a user and returns UserDetails, or throws UsernameNotFoundException.
  • UserDetails carries the password hash, authorities and four account-status flags.
  • DaoAuthenticationProvider calls the service, checks status flags, then verifies the password.
  • JdbcUserDetailsManager with the bundled users.ddl gives database-backed users with almost no code.
  • Unknown users, wrong passwords and disabled accounts all look identical to the client.

11. References