Sub topic 5
Users, UserDetailsService and password hashing
This chapter assumes you can write a Spring Boot REST controller, define @Bean methods, and read the filter chain setup from earlier chapters. You will register users, hash their passwords, and see how Spring Security checks a login against them.
How Spring Security finds a user
During HTTP Basic authentication, Spring Security needs two things. It needs a way to load a user by name, and a way to compare the submitted password with the stored one.
UserDetailsServiceloads aUserDetailsobject (username, stored password, authorities) by username.PasswordEncoderhashes passwords and checks a raw password against a stored hash.
If you define a bean of each type, Spring Boot wires them into a DaoAuthenticationProvider for you. The provider is the component that calls both.
Hash passwords, never store them
Never store a password as plain text or reversibly encrypt it. Store a hash. BCrypt is a deliberately slow hashing algorithm. It adds a random salt to each hash, so two users with the same password get different hashes. It is also slow on purpose, which makes guessing attacks expensive.
An in-memory user with a BCrypt hash
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);
}
}The encoder bean exists first, and the user service receives it as a parameter. The password is hashed with encoder.encode(...) before it goes into the UserDetails. The roles("USER") call stores the authority ROLE_USER, which is what hasRole("USER") checks.
An in-memory store suits demos and tests. Its users vanish on restart. For real systems, implement UserDetailsService yourself and load users from a database. Return a UserDetails whose password field holds the stored hash.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `There is no PasswordEncoder mapped for the id "null"` | A stored password has no `{bcrypt}` prefix and no encoder bean is defined | Define a `PasswordEncoder` bean, or prefix the stored hash |
| Login always returns 401 | The password was stored raw, so BCrypt cannot match it | Hash it with `encode` before saving |
| Spring prints a generated password at startup | No `UserDetailsService` bean exists, so Boot creates a default user | Define your own bean |
| `roles("ROLE_USER")` throws an exception | `roles` adds the `ROLE_` prefix itself | Pass `"USER"` or use `authorities("ROLE_USER")` |
Upgrading hashes over time
PasswordEncoderFactories.createDelegatingPasswordEncoder() stores the algorithm in the hash as a prefix, such as {bcrypt}. It can verify old hashes while new ones use a stronger algorithm. Consider it when you expect to change algorithms later.
Exercise
A teammate saves new users with userRepository.save(new AppUser(name, rawPassword)), and every login returns 401 even though the passwords are correct. What is wrong, and how do you fix it?
Show answer
The raw password is stored, but the BCryptPasswordEncoder compares the submitted password against a BCrypt hash, so matches can never succeed. Inject the PasswordEncoder into the registration code and save encoder.encode(rawPassword) instead. Existing rows must be re-hashed or the users must reset their passwords.