Re-encode a legacy password only after a successful match, then replace the stored hash with a conditional update.
Spring password hash upgrade after a verified login
Verify before migration
A user account holds a stored password hash with an algorithm marker. DelegatingPasswordEncoder can choose the correct verifier for that marker and use a current encoder for new hashes. On a successful login, upgradeEncoding tells the application whether the stored encoding should be replaced. This is a write to credential state, not a reason to retain or log the raw password. Password storage basics] cover the format; this lesson covers rolling a live account set forward.
Protect concurrent changes
Two successful logins can both observe the old hash. A compare-and-set update keyed by user ID and old hash lets only one write the replacement; the other can safely continue because its credential check already succeeded. A password reset racing with login must win over a stale rehash, so do not update by user ID alone. If a legacy hash lacks an algorithm marker, define an explicit migration mapping rather than silently treating an unknown format as plaintext.
Measure the rollout
Count remaining legacy IDs and successful upgrades without emitting hashes or passwords. Exercise a successful legacy login, a failed password, a concurrent reset and a user whose hash is already current. Rehashing costs CPU and may increase login latency; cap login concurrency and tune the selected algorithm on deployment hardware. An upgrade-on-login path will never reach dormant accounts, so set a separate reset policy if the old format must be retired by a date.
Implementation contract
public void verifyAndUpgrade(String rawPassword, Account account) {
String observedHash = account.passwordHash();
if (!passwordEncoder.matches(rawPassword, observedHash)) {
throw new BadCredentialsException("Invalid credentials");
}
if (passwordEncoder.upgradeEncoding(observedHash)) {
String replacement = passwordEncoder.encode(rawPassword);
accounts.updateHashIfCurrent(
account.id(), observedHash, replacement);
}
}Cost and verification
A password hash intentionally consumes CPU and memory. A login that upgrades pays one verification plus one new encoding, and the conditional database update adds a write. Rate limits and capacity planning matter during a broad migration.
Common Mistakes
- Do not re-encode before confirming that the supplied password matches.
- Do not overwrite a concurrent password reset with a stale login upgrade.
- Do not log raw passwords, stored hashes or replacement hashes during migration.
Read next
Spring PasswordEncoder: salted verification rather than reversible storage, Spring Session principal index: invalidate one operator's sessions safely, Spring Security 401 versus 403: authentication and access are separate failures, Spring method security: authorization advice runs through the bean proxy, Spring Security filter chain: authentication, CSRF and request order.
