Sub topic 5
Users, UserDetailsService and password hashing
This chapter assumes you can write a Spring Boot REST controller, define @Bean methods, and read Java lambdas. It also assumes you know that authentication means proving who a caller is. The previous chapters showed how a request reaches the authentication step. This chapter covers where Spring Security finds the user and how it checks the password.
What Spring Security needs from you
When a request carries a username and password, Spring Security must answer two questions:
- Does a user with this name exist?
- Does the submitted password match the stored one?
It delegates both questions to two small abstractions.
UserDetailsServiceloads a user by username.PasswordEncoderhashes passwords and compares a raw password with a stored hash.
You provide each as a @Bean. Spring Boot's default setup and the DaoAuthenticationProvider pick them up automatically. Spring Boot does not auto-configure the provider if you define your own AuthenticationProvider or AuthenticationManager.
UserDetails: the user as Spring Security sees it
UserDetailsService has one method: UserDetails loadUserByUsername(String username). It throws UsernameNotFoundException when no user exists.
A UserDetails object exposes:
- the username and the stored (hashed) password;
- a collection of
GrantedAuthorityvalues, which are the roles and permissions; - four status flags: account enabled, account not expired, account not locked, and credentials not expired.
If any flag says the account is unusable, authentication fails even when the password is right. This is how you disable or lock accounts without deleting them.
Hash passwords with a PasswordEncoder
Never store passwords in plain text, and never encrypt them in a way you can reverse. Store a hash instead. A hash is a one-way function. You cannot recover the password from it, but you can hash a login attempt and compare.
General-purpose hashes such as SHA-256 are fast, which helps an attacker who steals the database and tries billions of guesses. Password hashing algorithms are deliberately slow and use a random salt, a random value mixed into each hash. The salt means two users with the same password get different hashes, and precomputed tables become useless.
Spring Security's PasswordEncoder interface has two main methods:
String encode(CharSequence raw)returns a salted hash.boolean matches(CharSequence raw, String encoded)checks a login attempt.
BCryptPasswordEncoder is the usual choice. It stores the salt inside the hash string itself, so you need no extra column.
An in-memory user
The following configuration registers a BCrypt encoder and a single user. It suits demos and tests, not production.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
public class UserConfig {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
UserDetailsService userDetailsService(PasswordEncoder encoder) {
var user = User.withUsername("alice")
.password(encoder.encode("change-me"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}Three details matter here.
- The password passed to
.password(...)must already be encoded. The builder stores what you give it. .roles("USER")adds the authorityROLE_USER. Spring adds theROLE_prefix for you. If you use.authorities("ROLE_USER")you must write the prefix yourself.InMemoryUserDetailsManagerkeeps users in memory, and they disappear when the application stops.
Where the default user comes from
If you define no UserDetailsService, Spring Boot creates an in-memory user named user with a random password. It prints the password in the startup log. This helps for a first experiment. As soon as you define your own UserDetailsService bean, the default user is no longer created.
You can also set a fixed development user with properties:
spring.security.user.name=dev
spring.security.user.password=dev-only-password
spring.security.user.roles=USERUse this only on a local machine. Never commit real credentials.
Loading users from a database
In a real API you implement UserDetailsService yourself and read from your user table. The example below assumes a Spring Data JPA repository with a findByUsername method returning an Optional. It also assumes AppUser has a username, a password hash, a comma-separated roles string, and an enabled flag.
import java.util.Arrays;
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.stereotype.Service;
@Service
public class DatabaseUserDetailsService implements UserDetailsService {
private final AppUserRepository users;
public DatabaseUserDetailsService(AppUserRepository users) {
this.users = users;
}
@Override
public UserDetails loadUserByUsername(String username) {
AppUser appUser = users.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("Unknown user"));
return User.withUsername(appUser.getUsername())
.password(appUser.getPasswordHash())
.roles(Arrays.stream(appUser.getRoles().split(","))
.map(String::trim)
.toArray(String[]::new))
.disabled(!appUser.isEnabled())
.build();
}
}Because the class is a @Service and implements UserDetailsService, Spring Boot uses it as the user source. Keep the PasswordEncoder bean from the previous example so Spring can compare hashes.
Notes on this design:
- Return the stored hash as it is. Do not decode or re-encode it inside this method.
- Keep the exception message generic. The client should not be able to tell "no such user" from "wrong password". Spring Security's default provider hides this difference by default.
- The
Userbuilder is convenient. For extra fields such as a user ID, write your own class that implementsUserDetails, or extendUser.
Delegating encoders and upgrading hashes
Hashing advice changes over time. A hash you store today may be too weak in five years. Spring Security addresses this with DelegatingPasswordEncoder. It prefixes each stored hash with an algorithm identifier:
{bcrypt}$2a$10$7EqJtq98hPqEX7fNZaFWoOhi5BaoeSbzFFkYHgJ5Y1zv4X8y0u5seThe prefix tells Spring which algorithm to use when checking the password. You create one with:
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();It encodes new passwords with the current default (BCrypt) and can still verify older prefixed hashes. If a stored hash has no prefix and no delegating encoder is configured, you see There is no PasswordEncoder mapped for the id "null". That error means a plain {noop} or unprefixed value met a delegating encoder.
Other encoders worth knowing:
| Encoder | Notes |
|---|---|
| `BCryptPasswordEncoder` | Widely supported, a safe default. Strength (cost) defaults to 10. |
| `Argon2PasswordEncoder` | Memory-hard. Needs the Bouncy Castle library. |
| `SCryptPasswordEncoder` | Memory-hard. Needs Bouncy Castle. |
| `Pbkdf2PasswordEncoder` | Standards-based, no extra library. |
| `NoOpPasswordEncoder` | Stores plain text. Deprecated. Never use outside throwaway tests. |
Tuning the cost
BCrypt takes a strength parameter, from 4 to 31. Each increase doubles the work.
PasswordEncoder encoder = new BCryptPasswordEncoder(12);Pick a value that makes one hash take roughly 100 to 500 milliseconds on your production hardware. Slower is safer against attackers but also costs you CPU on every login. Because the cost is stored inside each hash, you can raise it later and old hashes still verify.
Common errors
- Encoded password looks wrong, login always fails. You passed a raw password to
.password(...). Encode it first, or use a{noop}prefix with a delegating encoder in tests. There is no PasswordEncoder mapped for the id "null". The stored value has no{id}prefix, but the encoder is a delegating one. Either prefix the stored hash or declare a specific encoder such asBCryptPasswordEncoderas the bean.- Role checks fail with a user who has the role. You stored
ADMINas an authority but checkhasRole("ADMIN"), which looks forROLE_ADMIN. Use.roles("ADMIN")or storeROLE_ADMIN. - Hashing the password twice. Encoding in the registration code and again in a JPA entity listener produces a hash of a hash.
- Returning
nullfromloadUserByUsername. ThrowUsernameNotFoundExceptioninstead. - Logging passwords. Do not log request bodies for login or registration endpoints.
Registering users safely
When your API creates users, hash the password before saving and never return the hash in a response.
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class RegistrationService {
private final AppUserRepository users;
private final PasswordEncoder encoder;
public RegistrationService(AppUserRepository users, PasswordEncoder encoder) {
this.users = users;
this.encoder = encoder;
}
public void register(String username, String rawPassword) {
AppUser user = new AppUser();
user.setUsername(username);
user.setPasswordHash(encoder.encode(rawPassword));
user.setRoles("USER");
user.setEnabled(true);
users.save(user);
}
}Also validate the password length and reject empty values before calling encode. Do not log rawPassword.
Exercise
A teammate defines a UserDetailsService with User.withUsername("bob").password("secret").roles("USER").build() and a BCryptPasswordEncoder bean. Login with bob/secret always fails. What is wrong, and how do you fix it?
Show answer
The stored password "secret" is plain text, not a BCrypt hash. The encoder's matches method hashes nothing. It expects a hash and cannot match a plain string, so every login fails. Fix it by passing encoder.encode("secret") to .password(...), or by storing a real BCrypt hash from the database. Never store the raw value.
Exercise
You store the authority "ADMIN" for a user, and the filter chain uses hasRole("ADMIN"). The user gets 403 on admin paths. Why, and what are two ways to fix it?
Show answer
hasRole("ADMIN") checks for the authority "ROLEADMIN". The user only has "ADMIN". Either build the user with .roles("ADMIN"), which adds the ROLE prefix, or change the rule to hasAuthority("ADMIN") so it matches the stored value.