Skip to lesson

UserDetails and UserDetailsService

Accounts now sit in MySQL, but Spring Security knows nothing about them. It must be able to ask who a person is, and an unknown e-mail must get exactly the same answer as a wrong password.

What Spring Security needs from a user: UserDetails

UserDetails is the Spring Security interface that describes one user during sign-in: the username, the stored password hash, the authorities and account flags such as enabled and locked.

Spring Security does not care where user data lives, only that it can ask these questions. This is the interface.

UserDetails.javaJava
public interface UserDetails extends Serializable {    Collection<? extends GrantedAuthority> getAuthorities();    String getPassword();           // the stored hash, e.g. {bcrypt}$2a$10$...    String getUsername();           // for ShopLite: the e-mail    default boolean isAccountNonExpired() { return true; }    default boolean isAccountNonLocked() { return true; }    default boolean isCredentialsNonExpired() { return true; }    default boolean isEnabled() { return true; }}

getPassword() returns the stored hash, not the typed password. The three flags isAccountNonLocked(), isAccountNonExpired() and isCredentialsNonExpired() are default methods that return true in Spring Security 7, so override them only when you need them. Every application stores users differently (a JPA table, LDAP, a legacy service), which is why this is an interface; the in-memory development user of the previous module was one too.

An authority is a plain permission string. A role is an authority with the ROLE_ prefix, so ShopLite's Role.CUSTOMER becomes ROLE_CUSTOMER. The Roles & Permissions module uses them for access rules.

Adapting the User entity: a separate UserPrincipal

CredentialsContainer is a Spring Security interface with one method, eraseCredentials(), that a user object implements so its secrets, such as the password hash, are cleared after a successful sign-in.

UserPrincipal is a small class that copies what security needs out of the User entity. UserPrincipal.from(user) is the adapter.

Example 1 · src/main/java/com/shoplite/user/UserPrincipal.java

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

UserPrincipal.javaJava
package com.shoplite.user;
import java.util.Collection;import java.util.List;
import org.springframework.security.core.CredentialsContainer;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;
/** * What Spring Security knows about a signed-in ShopLite user: a small, plain copy of the * User entity, so the entity (and its lazy fields) never travels through the security code. */public final class UserPrincipal implements UserDetails, CredentialsContainer {
    private final Integer id;    private final String email;    private String passwordHash;    private final boolean enabled;    private final Integer customerId;    private final List<GrantedAuthority> authorities;
    private UserPrincipal(Integer id, String email, String passwordHash, boolean enabled,                          Integer customerId, List<GrantedAuthority> authorities) {        this.id = id;        this.email = email;        this.passwordHash = passwordHash;        this.enabled = enabled;        this.customerId = customerId;        this.authorities = authorities;    }
    static UserPrincipal from(User user) {        List<GrantedAuthority> authorities = user.getRoles().stream()                .sorted()                .map(role -> (GrantedAuthority) new SimpleGrantedAuthority("ROLE_" + role.name()))                .toList();        Integer customerId = user.getCustomer() == null ? null : user.getCustomer().getId();        return new UserPrincipal(user.getId(), user.getEmail(), user.getPasswordHash(), user.isEnabled(),                customerId, authorities);    }
    public Integer getId() { return id; }
    /** null for staff accounts. */    public Integer getCustomerId() { return customerId; }
    @Override    public String getUsername() { return email; }
    @Override    public String getPassword() { return passwordHash; }
    @Override    public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; }
    @Override    public boolean isEnabled() { return enabled; }
    /** Called by Spring Security after a successful sign-in: the hash is not needed any more. */    @Override    public void eraseCredentials() {        this.passwordHash = null;    }
    @Override    public String toString() {        return "UserPrincipal[id=" + id + ", email=" + email + ", authorities=" + authorities + "]";    }}
Sample output
$ curl -u asha.rao@example.com:asha-dev-password http://localhost:8080/api/v1/customers/1
{"id":1,"fullName":"Asha Rao","email":"asha.rao@example.com","phone":"9876543201","createdAt":"2026-05-04T10:15:00+05:30"}

Server log (logging.level.org.springframework.security=DEBUG):
DEBUG o.s.security.web.FilterChainProxy        : Securing GET /api/v1/customers/1
DEBUG o.s.s.a.dao.DaoAuthenticationProvider    : Authenticated user
DEBUG o.s.s.w.a.www.BasicAuthenticationFilter  : Set SecurityContextHolder to UsernamePasswordAuthenticationToken [Principal=UserPrincipal[id=2, email=asha.rao@example.com, authorities=[ROLE_CUSTOMER]], Credentials=[PROTECTED], Authenticated=true, ...]
DEBUG o.s.security.web.FilterChainProxy        : Secured GET /api/v1/customers/1

What this code does

  • from(user) copies the plain values out of the entity and turns each Role into ROLE_ + its name. getCustomer().getId() on the lazy proxy needs no query.
  • The DEBUG line shows the result in the SecurityContext: the principal is a UserPrincipal, and Spring prints the credentials as [PROTECTED].
  • eraseCredentials() clears the hash after sign-in; toString() never includes it.

Why not let the User entity implement UserDetails directly? After sign-in, the principal lives in the SecurityContext for the whole request and later in a token or a session. An entity there drags along lazy fields that fail outside a transaction, ties security to the table layout and keeps the hash in memory.

After a successful sign-in, Spring's ProviderManager calls eraseCredentials() and the hash is set to null: no later code, log line or debugger can see it.

Implementing UserDetailsService.loadUserByUsername

UserDetailsService is the Spring Security interface with one method, loadUserByUsername, that finds a user by the name typed at sign-in and returns a UserDetails, or throws UsernameNotFoundException.

ShopLite's DatabaseUserDetailsService normalises the typed e-mail, asks the repository and adapts the result to a UserPrincipal.

Example 2 · src/main/java/com/shoplite/user/DatabaseUserDetailsService.java

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
package com.shoplite.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;
/** Spring Security asks this class for a user by the name typed at sign-in (for ShopLite, the e-mail). */@Serviceclass DatabaseUserDetailsService implements UserDetailsService {
    private final UserRepository users;
    DatabaseUserDetailsService(UserRepository users) {        this.users = users;    }
    @Override    public UserDetails loadUserByUsername(String username) {        String email = Emails.normalise(username);        return users.findByEmail(email)                .map(UserPrincipal::from)                .orElseThrow(() -> new UsernameNotFoundException("No account for the given e-mail"));    }}
Sample output
$ mvn spring-boot:run
...
INFO r$InitializeUserDetailsManagerConfigurer : Global AuthenticationManager configured with UserDetailsService bean with name databaseUserDetailsService
INFO com.shoplite.ShopliteApiApplication      : Started ShopliteApiApplication in 31.096 seconds

$ curl -s -o /dev/null -w "%{http_code}\n" -u "asha.rao@example.com:asha-dev-password" http://localhost:8080/api/v1/customers/1
200
$ curl -s -o /dev/null -w "%{http_code}\n" -u " Asha.Rao@Example.com:asha-dev-password" http://localhost:8080/api/v1/customers/1
200
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/customers/1
401

What this code does

  • The startup line proves Spring found the bean and uses it for every sign-in. No extra configuration class is needed.
  • Emails.normalise trims and lower-cases the typed name, so " Asha.Rao@Example.com" signs in as well.
  • The class is package-private: only Spring calls it. Without credentials the request still gets 401, as in the previous module.

Example 3 · Mistake: lazy roles read after the repository call

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
// UserRepository.java without the entity graphOptional<User> findByEmail(String email);
// UserPrincipal.from(user) then calls user.getRoles() after the repository call has ended
Sample output
DEBUG org.hibernate.SQL : select u1_0.user_id,u1_0.created_at,u1_0.customer_id,u1_0.email,u1_0.enabled,u1_0.password_hash from app_user u1_0 where u1_0.email=?
org.hibernate.LazyInitializationException: Cannot lazily initialize collection of role 'com.shoplite.user.User.roles' with key '2' (no session)

What this code does

  • Without @EntityGraph, the SELECT has no join and the roles stay unloaded. The repository's transaction ends when findByEmail returns.
  • Reading getRoles() afterwards needs a database session that no longer exists: LazyInitializationException. During a real sign-in this becomes a confusing 401 with the cause hidden in the DEBUG log.
  • Fix: @EntityGraph(attributePaths = "roles") on findByEmail, as in the User entity lesson. Do not switch on open-in-view or EAGER fetching to hide it.

Because the class is a @Service bean, Spring Boot wires it into the global AuthenticationManager together with the PasswordEncoder bean; the log says so in one line. Boot then stops creating the in-memory user, so delete the spring.security.user.* lines from application-dev.properties.

What can go wrong: two UserDetailsService beans (Boot wires neither and logs a warning), forgetting to normalise the e-mail (Asha.Rao@Example.com is not found), and lazy roles loaded after the repository call (Example 3).

UsernameNotFoundException and not revealing whether the e-mail exists

Account enumeration is an attack where someone learns which e-mail addresses have accounts by comparing your answers for known and unknown users, then targets those people with phishing or password guessing.

A wrong password and an unknown e-mail must look the same to the caller. Example 4 sends both requests.

Example 4 · Wrong password and unknown e-mail give the same answer

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Terminal
# The same request twice: an existing account with a wrong password,# then an e-mail with no account at allcurl -i -u "asha.rao@example.com:wrong-password-123" http://localhost:8080/api/v1/customers/1curl -i -u "nobody@example.com:wrong-password-123" http://localhost:8080/api/v1/customers/1
Sample output
$ curl -i -u "asha.rao@example.com:wrong-password-123" http://localhost:8080/api/v1/customers/1
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Type: application/json

{"timestamp":"2026-10-16T07:24:51.952Z","status":401,"error":"Unauthorized","path":"/api/v1/customers/1"}

$ curl -i -u "nobody@example.com:wrong-password-123" http://localhost:8080/api/v1/customers/1
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Type: application/json

{"timestamp":"2026-10-16T07:24:52.359Z","status":401,"error":"Unauthorized","path":"/api/v1/customers/1"}

Average time of 10 failed sign-ins each (your numbers will differ):
sneha.patil@example.com (exists, wrong password)  153 ms
nobody@example.com      (does not exist)          136 ms

Server log, DEBUG only (never sent to the client):
DEBUG o.s.s.a.dao.DaoAuthenticationProvider : Failed to authenticate since password does not match stored value
DEBUG o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user 'nobody@example.com'
org.springframework.security.authentication.BadCredentialsException: Bad credentials

What this code does

  • The client sees two identical 401 responses (only the timestamp differs). Nothing tells it whether nobody@example.com has an account.
  • The times are close too: for an unknown e-mail, Spring still runs one BCrypt check against a dummy hash. Single timings are noisy, so compare averages.
  • Only the server log at DEBUG level knows the real reason. That log is for you, not for the caller.

UsernameNotFoundException never reaches the client: Spring Security turns it into the same BadCredentialsException ("Bad credentials") as a wrong password, so both answers are an identical 401. Spring even spends about the same time on an unknown e-mail, by checking the typed password against a dummy hash, so a stopwatch gives nothing away either.

Keep it that way in your own code: the exception message is for the server log only and never contains the password. The login endpoint in the JWT module uses one generic message for both cases.

hideUserNotFoundExceptions is true by default in DaoAuthenticationProvider. Leave it so.

How DaoAuthenticationProvider uses the UserDetailsService and PasswordEncoder

DaoAuthenticationProvider is the Spring Security component that checks a username and a password: it loads the user with a UserDetailsService and compares the typed password with the stored hash using a PasswordEncoder.

The HTTP Basic filter hands the typed values to the AuthenticationManager, which asks this provider. The picture shows one check.

One sign-in check. The Basic filter reads the e-mail and password. DaoAuthenticationProvider asks DatabaseUserDetailsService for the user from MySQL, then asks the PasswordEncoder to match the typed password with the hash. On success the user goes into the SecurityContext. Both failures give 401.

Example 5 · DaoProviderDemo.java: the provider without a web server

Runs in: a small Maven project with spring-security-core (versions from Spring Boot 4.1.1)

DaoProviderDemo.javaJava
import java.util.Map;
import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.ProviderManager;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.authentication.dao.DaoAuthenticationProvider;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;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.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.crypto.password.PasswordEncoder;
public class DaoProviderDemo {
    public static void main(String[] args) {        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        // A pretend users table: e-mail -> stored hash, enabled flag and role        Map<String, UserDetails> table = Map.of(                "asha.rao@example.com", User.withUsername("asha.rao@example.com")                        .password(encoder.encode("asha-dev-password")).roles("CUSTOMER").build(),                "ravi.kumar@example.com", User.withUsername("ravi.kumar@example.com")                        .password(encoder.encode("ravi-dev-password")).roles("CUSTOMER").disabled(true).build());
        UserDetailsService users = email -> {            UserDetails user = table.get(email);            if (user == null) {                throw new UsernameNotFoundException("No account for the given e-mail");            }            return user;        };
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider(users);        provider.setPasswordEncoder(encoder);
        AuthenticationManager manager = new ProviderManager(provider);   // what httpBasic and login call
        signIn(manager, "asha.rao@example.com", "asha-dev-password");        signIn(manager, "asha.rao@example.com", "wrong-password-123");        signIn(manager, "nobody@example.com", "asha-dev-password");        signIn(manager, "ravi.kumar@example.com", "ravi-dev-password");    }
    static void signIn(AuthenticationManager manager, String email, String password) {        Authentication request = UsernamePasswordAuthenticationToken.unauthenticated(email, password);        try {            Authentication result = manager.authenticate(request);            UserDetails principal = (UserDetails) result.getPrincipal();            System.out.println(email + " -> signed in");            System.out.println("    authorities: " + result.getAuthorities());            System.out.println("    typed password kept: " + (result.getCredentials() != null)                    + ", hash kept: " + (principal.getPassword() != null));        } catch (AuthenticationException e) {            System.out.println(email + " -> " + e.getClass().getSimpleName() + ": " + e.getMessage());        }    }}
Sample output
asha.rao@example.com -> signed in
    authorities: [ROLE_CUSTOMER, FactorGrantedAuthority [authority=FACTOR_PASSWORD, issuedAt=2026-10-16T07:58:39.553622100Z]]
    typed password kept: false, hash kept: false
asha.rao@example.com -> BadCredentialsException: Bad credentials
nobody@example.com -> BadCredentialsException: Bad credentials
ravi.kumar@example.com -> DisabledException: User is disabled

What this code does

  • This is what the HTTP Basic filter does on every request: build an unauthenticated token from the typed values and pass it to the AuthenticationManager.
  • A wrong password and an unknown e-mail both end as BadCredentialsException: Bad credentials; a disabled account gives DisabledException. All three become 401 for an HTTP client.
  • After success ProviderManager erased both the typed password and the stored hash. Spring Security 7 adds the FACTOR_PASSWORD authority; the issuedAt time differs on every run.

The password is never decoded, because a hash cannot be decoded. A disabled or locked account fails before the comparison with DisabledException or LockedException; on success the provider builds an authenticated token with the principal and its authorities.

Spring Security 7 adds one more authority on success, FACTOR_PASSWORD, which records that a password was used. It is the basis for multi-factor rules; ShopLite can ignore it for now.

Order of execution

Put the sign-in check in order

What DaoAuthenticationProvider does after the Basic filter hands it the typed values.

Next step

Check your understanding

12 quick questions