Practice: users and password storage
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Password-storage bugs come from a short list of habits: storing the password instead of a hash, letting it reach a response or a log, hashing outside the shared encoder, and sign-in code that reveals which e-mails exist.
Reading a stored hash
A stored hash can be read at a glance: {bcrypt}, $2a$, 10$, then 22 characters of salt and 31 of hash. Example 1 is the real table.
Example 1 · Reading the app_user table
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
SELECT user_id, email, password_hash, enabled, customer_id FROM app_user;$ mysql -u root -p shoplite -e "SELECT user_id, email, password_hash, enabled, customer_id FROM app_user"
user_id email password_hash enabled customer_id
1 admin@shoplite.example {bcrypt}$2a$10$I8Y8ApR1o0xHK5Pjl.psm.6505DA.Vsi5Ou8ydn8H8yISdoNzUbgS 1 NULL
2 asha.rao@example.com {bcrypt}$2a$10$tf367IbGb5L.PfxIpb8Uq.hnqlV4KsvaVloXYH/WlwE5GbZ55aWvG 1 1
3 sneha.patil@example.com {bcrypt}$2a$10$5moS5F2d4t7gk77MBH.OOeL6Y1s0TvxYr6l/eEEZtJkgKiCHA63rO 1 9What this code does
- Every hash starts with
{bcrypt}$2a$10$: made by the delegating encoder with BCrypt at cost 10. - Asha's and Sneha's hashes share nothing even though both are cost 10: each has its own 22-character salt.
- The admin has
customer_idNULL (a staff account); the other two point at their customer rows.
A row that does not start with {bcrypt}$2a$ (or another known {id}) did not come from passwordEncoder.encode and will fail at sign-in. Other bad signs: cost 4, a 64-character hex string (plain SHA-256), or a readable password.
In ShopLite every row has the same shape, and two users with the same password still get different rows because of the salt.
Predict the output
Which stored value is wrong?
Read each value in a password_hash column.
Round 1 of 3
A row in app_user.
Mistake: storing, logging or returning the password
Plain passwords leak through ordinary code. Example 2 is a seed line that stores a good hash the wrong way.
Example 2 · Mistake: a hash without its {bcrypt} prefix
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
-- A hand-written seed line: the hash was copied from an online BCrypt generator, without {bcrypt}UPDATE app_userSET password_hash = '$2a$10$tf367IbGb5L.PfxIpb8Uq.hnqlV4KsvaVloXYH/WlwE5GbZ55aWvG'WHERE email = 'asha.rao@example.com';$ curl -i -u asha.rao@example.com:asha-dev-password http://localhost:8080/api/v1/customers/1
HTTP/1.1 500
Server log:
ERROR o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.IllegalArgumentException: Given that there is no default password encoder configured, each password must have a password encoding prefix. Please either prefix this password with '{noop}' or set a default password encoder in `DelegatingPasswordEncoder`.What this code does
- The hash itself is a valid BCrypt hash of
asha-dev-password, but without{bcrypt}the delegating encoder does not know which encoder to use. - The
IllegalArgumentExceptionescapes the sign-in filter, so the client gets a 500, not a 401. - Fix: store exactly what
passwordEncoder.encode(...)returns, prefix included, for example with a small hash tool built onPasswordEncoderFactories.
The leaks are new User(email, request.password(), ...), which stores the password itself; log.info("Sign-up {}", request), which prints it through a record's toString(); and returning the entity, which sends the hash to the client. Each has one fix:
- Hash in the service with the shared
PasswordEncoderbean and store exactly whatencodereturns,{bcrypt}prefix included. - Give request records a masking
toString()and do not log bodies. - Return response records such as
UserResponsethat have no password or hash field.
A hash made somewhere else (an online generator, another encoder, a copy without its prefix) is a related trap: the delegating encoder refuses it and sign-in fails with a 500, as in the example above.
Mistake: sign-in code that leaks or breaks
Sign-in code has its own traps. Example 3 shows the one that stops the app at startup.
Example 3 · Mistake: no PasswordEncoder bean
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
// SecurityConfig.java with the passwordEncoder() @Bean method deleted// UserService still asks for a PasswordEncoder in its constructor:UserService(UserRepository users, CustomerRepository customers, PasswordEncoder passwordEncoder) { ...}$ mvn spring-boot:run ... *************************** APPLICATION FAILED TO START *************************** Description: Parameter 2 of constructor in com.shoplite.user.UserService required a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' that could not be found. Action: Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.
What this code does
UserServiceneeds aPasswordEncoderto hash at sign-up, but nothing defines one, so Spring stops at startup.- Spring Security's sign-in would quietly fall back to its own delegating encoder, which hides the problem until sign-up code needs the bean. One shared
@Beanmakes both use the same encoder. - The fix is the three-line
passwordEncoder()method inSecurityConfig.
loadUserByUsername has three classic bugs: it looks up the e-mail exactly as typed, it returns the entity (whose lazy roles fail outside the transaction), or it gives "no such e-mail" a different message or status than a wrong password.
The ShopLite version normalises with Emails.normalise, loads roles with @EntityGraph, returns a separate UserPrincipal and throws UsernameNotFoundException, which Spring turns into the same BadCredentialsException as a wrong password. A missing PasswordEncoder bean is the last trap.
Interview drill: how should passwords be stored?
A two-minute answer covers five points in order: never store or encrypt the password; hash it with a slow, salted algorithm (BCrypt with a measured cost, or Argon2); store the algorithm id with the hash ({bcrypt}) so it can change later; check with matches, never by comparing strings; and keep the hash out of every response, log and DTO.
Follow-ups usually ask why not SHA-256 (too fast), why a salt (defeats precomputed tables and hides equal passwords), what the cost factor is (2^cost rounds, doubles per step), what happens on a database leak (attackers must guess slowly, one user at a time), and how to handle forgotten passwords (a reset link, never sending the old one).
- Never: plain text, encryption, MD5, SHA-1 or SHA-256 alone
- Always: a PasswordEncoder bean,
{bcrypt}or{argon2...}prefix,matchesat sign-in - Validate at sign-up: 15-64 characters and at most 72 bytes for BCrypt
- Same 401 for unknown e-mail and wrong password; 409 only at sign-up
Order of execution
The two-minute answer
Put the points of a good answer in a sensible order.
Finish up
Mark complete & continue
Next: Mini project: ShopLite user accounts