← Back to FastAPI, page 4

fastapi-0075 · Medium mid

How should a FastAPI app hash and verify passwords with pwdlib (Argon2), upgrade old hashes on login and avoid user-enumeration timing leaks?

Use a purpose-built password hashing library such as pwdlib with Argon2id (bcrypt as a legacy option), never fast hashes like SHA-256. Store only the encoded hash, verify with PasswordHash.verify(), and call verify_and_update() on login to detect hashes that use older algorithms or parameters and replace them. Hash a dummy password when the user does not exist so response time does not reveal valid usernames. passlib is unmaintained and has issues with new bcrypt releases, which is why pwdlib is recommended.

Full answer

Requirements for password storage: slow, salted, memory-hard where possible, and upgradeable.

python
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher()))      # first hasher is used for new hashes
hashed = password_hash.hash("s3cret")                                # "$argon2id$v=19$m=65536,t=3,p=4$..."
password_hash.verify("s3cret", hashed)                               # True or False
ok, new_hash = password_hash.verify_and_update("s3cret", old_bcrypt_hash)
  • PasswordHash.recommended() returns an Argon2id configuration with safe defaults.
  • Each hash embeds the algorithm, parameters and a random salt, so no separate salt column is needed and identical passwords produce different hashes.
  • verify_and_update() returns (valid, updated_hash_or_None). If valid and the stored hash uses a legacy algorithm or weaker parameters, updated_hash is a fresh hash to save. This enables gradual migration from bcrypt (or a weaker cost) to Argon2 without forcing resets.

Login endpoint hygiene:

  • Look up the user; if none exists, still run a verification against a precomputed dummy hash so that unknown users cost the same time as wrong passwords. Return the same message ("Invalid credentials") for both.
  • Rate-limit attempts per account and IP, and add lockout or delays.
  • Run hashing off the event loop: it is CPU-heavy and blocking. Use a sync def endpoint (thread pool) or await anyio.to_thread.run_sync(password_hash.verify, ...). Hashing in async def freezes other requests.
  • Enforce minimum length (12 or more) and check against breached-password lists; avoid arbitrary composition rules; allow long passphrases (Argon2 and bcrypt have limits: bcrypt truncates at 72 bytes).
  • Never log or return passwords or hashes; do not email them.

Tune Argon2 cost so a hash takes roughly 50 to 250 ms on production hardware and re-evaluate yearly.

python
from typing import Annotated

from fastapi import Depends, FastAPI, Form, HTTPException
from fastapi.testclient import TestClient
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

legacy = PasswordHash((BcryptHasher(),))
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher()))      # Argon2id for new hashes, bcrypt still verifies
DUMMY_HASH = password_hash.hash("dummy-password-for-timing")

USERS = {"asha": {"hash": password_hash.hash("correct horse battery")},
         "ravi": {"hash": legacy.hash("old-bcrypt-password")}}

app = FastAPI()


@app.post("/login")
def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):     # sync def: runs in the thread pool
    user = USERS.get(username)
    stored = user["hash"] if user else DUMMY_HASH                  # same work for unknown users
    valid, updated = password_hash.verify_and_update(password, stored)
    if not user or not valid:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    if updated:
        user["hash"] = updated                                     # transparent upgrade to Argon2id
    return {"user": username}


print(USERS["asha"]["hash"].startswith("$argon2id$"), USERS["ravi"]["hash"].startswith("$2b$"))
print(USERS["asha"]["hash"] != password_hash.hash("correct horse battery"))      # random salt: hashes differ

c = TestClient(app)
print(c.post("/login", data={"username": "asha", "password": "correct horse battery"}).json())
print(c.post("/login", data={"username": "asha", "password": "wrong"}).json())
print(c.post("/login", data={"username": "nobody", "password": "x"}).json())
print(c.post("/login", data={"username": "ravi", "password": "old-bcrypt-password"}).json())
print("ravi upgraded:", USERS["ravi"]["hash"].startswith("$argon2id$"))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install "pwdlib[argon2,bcrypt]"`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pwdlib 0.4.2): True True True {'user': 'asha'} {'detail': 'Invalid credentials'} {'detail': 'Invalid credentials'} {'user': 'ravi'} ravi upgraded: True

Key points

  • Use Argon2id via pwdlib; never fast hashes
  • Hashes embed algorithm, parameters and salt
  • verify_and_update upgrades legacy hashes on login
  • Run a dummy verification for unknown users; same error message
  • Hash off the event loop; rate-limit logins

Common mistakes

  • Using SHA-256 or MD5 for passwords
  • Running hashing inside async def and blocking the event loop
  • Returning different messages or timings for unknown users
  • Truncation surprises with bcrypt's 72-byte limit
  • Using the unmaintained passlib in new projects

Follow-ups

  • How do you choose Argon2 parameters?
  • How do you force a password reset after a breach?
  • What is a pepper and does it help?

Tips

  • Say slow, salted, upgradeable
  • Describe verify_and_update
  • Mention the dummy hash for timing