Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Authentication Mechanisms

UserDetailsService, UserDetails and Password Encoders

Load users with UserDetailsService, model accounts with UserDetails, hash passwords with DelegatingPasswordEncoder and upgrade old hashes without forcing resets.

Username and password authentication needs two things: a way to find a user by name and a way to check a password against what is stored. Spring Security separates them into UserDetailsService (find) and PasswordEncoder (check). Nearly every custom login setup is built from these two interfaces, so it pays to know them well.

The real classes are shown read-only; the examples that run are Java stand-ins that mimic their contracts, including the hash format of the delegating encoder.

UserDetails: the account as security sees it

UserDetails is the interface Spring Security uses to represent an account. It is deliberately small:

Java
public interface UserDetails extends Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    String getPassword();
    String getUsername();
    boolean isAccountNonExpired();
    boolean isAccountNonLocked();
    boolean isCredentialsNonExpired();
    boolean isEnabled();
}

The four boolean flags are checked automatically during authentication. A disabled, locked or expired account throws a specific AuthenticationException (DisabledException, LockedException, ...), which makes "suspend this user" a one-column change in your database.

Your domain User entity can implement UserDetails directly, but many teams keep the entity free of framework types and return Spring's builder instead:

Java
UserDetails u = User.withUsername("alice")
        .password("{bcrypt}$2a$10$...")
        .roles("USER", "EDITOR")          // stores ROLE_USER and ROLE_EDITOR
        .build();

roles("X") is shorthand for the authority ROLE_X; authorities("report:read") stores the string as is. The roles and authorities lesson explains the difference.

UserDetailsService: find by username

Java
public interface UserDetailsService {
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

One method. Your implementation is a repository lookup:

Java
@Service
class AppUserDetailsService implements UserDetailsService {

    private final UserRepository users;

    AppUserDetailsService(UserRepository users) { this.users = users; }

    @Override
    public UserDetails loadUserByUsername(String email) {
        return users.findByEmailIgnoreCase(email)
            .map(u -> User.withUsername(u.getEmail())
                    .password(u.getPasswordHash())
                    .disabled(!u.isActive())
                    .authorities(u.getPermissions().toArray(String[]::new))
                    .build())
            .orElseThrow(() -> new UsernameNotFoundException("unknown user"));
    }
}

If a bean of this type exists, Boot's default in-memory user disappears (see auto-configuration) and DaoAuthenticationProvider uses yours. The ready-made implementations are InMemoryUserDetailsManager (tests and demos) and JdbcUserDetailsManager (see the JDBC user store).

UsernameNotFoundException is converted to a generic BadCredentialsException by default, so the client cannot tell a missing user from a wrong password. Do not turn that off (hideUserNotFoundExceptions) on a public application.

PasswordEncoder: never store a password

Java
public interface PasswordEncoder {
    String encode(CharSequence rawPassword);
    boolean matches(CharSequence rawPassword, String encodedPassword);
    default boolean upgradeEncoding(String encodedPassword) { return false; }
}

encode produces a salted, deliberately slow hash; matches recomputes it with the salt contained in the stored string. The recommended bean is the delegating encoder:

Java
@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

It writes new hashes as $2a$10$... and reads the prefix of old ones to pick the right algorithm. That prefix is the key to migration: you can introduce a stronger algorithm ({argon2@SpringSecurity_v5_8}) and old rows keep working because they carry their own label. Combined with upgradeEncoding, a successful login can silently rehash the password with the new default (UserDetailsPasswordService). The details of choosing algorithms and cost live in password storage and hardening.

A delegating encoder you can run

The stand-in implements the same hash convention with two schemes (a legacy plain digest and a salted iterated one) and shows an upgrade on login. It uses only the JDK.

Java Delegating encoder with transparent upgrade (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the same password encoded twice gives different strings: the random salt prevents an attacker from spotting users with identical passwords and defeats precomputed tables. This stand-in uses iterated SHA-256 only so it runs here; in a real application use the real BCrypt, Argon2 or SCrypt encoders, which resist GPU attacks far better.

An in-memory user store for tests

For small demos, tests and the second runnable example, a map-backed store with the same contract as UserDetailsService is enough. It also demonstrates the account flags and the "unknown user looks like a wrong password" rule.

Java UserDetailsService contract with account flags (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the order in the real framework: DaoAuthenticationProvider runs its pre-checks (locked, disabled, expired account) before the password check, and the credentials-expired check after it. That means a locked or disabled account reveals itself even to someone who does not know the password. Public applications that care about this show the same generic message for all failures and keep the detail in the log.

Design tips

  • Key by a stable unique value, usually email, and normalize case once, in one place.
  • Load authorities with the user in a single query to avoid N+1 lookups on every login.
  • Return a copy without the password to the rest of the app: Authentication.getPrincipal() may be serialized into the session. Use eraseCredentials (on by default for the provider's result) and never put the hash into JSON.
  • Cache with care. A UserDetailsService that caches users keeps a banned account active until the cache expires.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the job of UserDetailsService?

    It only finds the user. Password comparison belongs to the PasswordEncoder, called by the authentication provider.
  2. 2. What does the prefix in {bcrypt}$2a$10$... tell DelegatingPasswordEncoder?

    The id selects the encoder, so different algorithms can coexist and old hashes can be upgraded gradually.
  3. 3. Why do two encodings of the same password differ?

    A random salt defeats precomputed tables and hides equal passwords.
  4. 4. Which flag makes it easy to suspend an account without deleting it?

    A disabled account fails authentication with DisabledException after the password check.

Summary

  • UserDetails models the account (name, hash, authorities, status flags); UserDetailsService loads it by username.
  • A UserDetailsService bean replaces Boot's generated default user.
  • Always hash with a PasswordEncoder; createDelegatingPasswordEncoder() allows upgrades through the prefix.
  • Missing users are reported as bad credentials so usernames are not revealed.
  • Load authorities with the user and keep hashes out of responses.

Next: AuthenticationManager and providers