Video in progress

Middle 🌱 Spring

How should user passwords be stored, and how is that done in Spring?

You don't store passwords in plain text, and not with a plain hash (MD5, SHA-256) either. You need a slow, salted algorithm — BCrypt, Argon2 or PBKDF2. In Spring, PasswordEncoder does this.

📖 Answer

@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder(); // default: bcrypt
}

// on sign-up
user.setPasswordHash(encoder.encode(rawPassword));

// on check (Spring Security does this itself)
encoder.matches(rawPassword, user.getPasswordHash());

In the database it looks like this:

{bcrypt}$2a$10$Nq3T...

The {bcrypt} prefix is for DelegatingPasswordEncoder. If you later switch algorithms (say, to argon2), old passwords still verify, and new ones are written with the new algorithm.

Why is SHA-256 no good? It's too fast — a GPU tries billions of candidates per second. BCrypt is deliberately slow (it has a cost factor) and adds a random salt to every password, so rainbow tables don't help.

Also: rate-limit login attempts, never log passwords, and make "wrong password" and "user not found" the same message.