Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 50 ยท Authentication and security

Password hashing and user accounts

Store passwords safely in FastAPI: why you hash, how salts and slow hashes work, a live PBKDF2 stand-in, pwdlib with Argon2, and a registration flow.

If your API has user accounts, it has passwords, and a database leak is a matter of when, not if. What matters is what the attacker finds. If your table holds the passwords themselves, every user is compromised, including on other sites where they reused the password. If it holds properly hashed passwords, the attacker has to guess each one at great cost.

This lesson explains what a good password hash is, builds one you can run in the browser, shows the library you would use in production, and then wires it into a registration and login flow with FastAPI.

Encrypt, hash, or store?

Three words get mixed up:

  • Plain text: never. Anyone with database access, backups or logs reads it.
  • Encryption: reversible with a key. If the key leaks along with the database, all passwords leak. You never need to read a password back, so reversibility is only a risk.
  • Hashing: a one-way function. You store the hash; at login you hash the typed password and compare. Nobody, including you, can turn the hash back into the password.

What makes a password hash good

Salted A random value per user.
Slow on purpose Thousands of rounds per guess.
One-way No function turns it back.
Adjustable You can raise the cost over time.
1 / 2

A salt is random data stored next to the hash and mixed into it. Two users with the password hunter2 get different hashes, and an attacker cannot use one precomputed table ("rainbow table") against everybody.

A slow hash (also called a key-derivation function) repeats its work thousands of times, or demands lots of memory. A fast hash like SHA-256 can be tried billions of times per second on a GPU. A slow one turns that into thousands, which makes brute force impractical for decent passwords.

Slow hashing you can run here

The standard library has hashlib.pbkdf2_hmac and hashlib.scrypt. The browser's Python build does not include them, so the live examples use a small implementation of PBKDF2-HMAC-SHA256 built on hmac, which is part of every build. For a 32-byte output PBKDF2 is only a short loop, and it produces exactly the same bytes as the standard library function. In production you would call the library instead; the sketch is below.

Python
# Normal Python, read-only here
import hashlib, os
salt = os.urandom(16)
digest = hashlib.pbkdf2_hmac("sha256", b"correct horse", salt, 600_000)
Python Salts, rounds and constant-time comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the stored format algorithm$rounds$salt$digest. Everything needed to verify later is in the string: the algorithm, the cost and the salt. That is why you can raise ROUNDS next year and still verify old hashes, then re-hash users on their next login.

hmac.compare_digest compares in constant time. A normal == stops at the first different character, and measuring that tiny timing difference can leak information about the hash. For password hashes the risk is small, but the habit is free.

Do not write your own cryptography in a real project. The stand-in above exists because the browser build lacks the standard function. Production code should use hashlib.pbkdf2_hmac/scrypt or, better, a library such as pwdlib with Argon2.

What to use in production

The FastAPI community moved from passlib (unmaintained) to pwdlib, which wraps modern algorithms and handles the format and upgrades for you.

Python
# Read-only: needs `pip install "pwdlib[argon2]"`
from pwdlib import PasswordHash

password_hash = PasswordHash.recommended()      # Argon2id by default

hashed = password_hash.hash("hunter2")
ok = password_hash.verify("hunter2", hashed)

ok, new_hash = password_hash.verify_and_update("hunter2", hashed)
if ok and new_hash:
    ...   # settings changed: store the upgraded hash

Argon2id is the current first choice because it is memory-hard, which hurts GPU attackers. bcrypt is older but still widely used (it truncates passwords at 72 bytes). scrypt and PBKDF2 are acceptable when you cannot install a library; for PBKDF2-SHA256 use hundreds of thousands of rounds.

Hashing is deliberately CPU-heavy: tens of milliseconds per call. Inside an async def endpoint that blocks the event loop (see async def vs def endpoints). In a real app run it in the thread pool: write the endpoint as plain def, or call await run_in_threadpool(password_hash.hash, password). The live examples keep the work small instead, because the browser has no threads.

A registration and login flow

The flow has four rules:

  1. Validate input with a Pydantic model (see Field constraints and validators): sensible minimum length, no silly maximum below 64 characters.
  2. Store only the hash, never the password.
  3. Never return the hash: use a separate response model (Response models and nested data).
  4. At login, give the same error for "unknown user" and "wrong password", so attackers cannot discover which emails are registered. To also hide timing, run a hash check against a dummy hash for unknown users.
Python Register and log in with hashed passwords

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the results in order: registration returns 201 with only id and email; the duplicate returns 409; the short password is rejected by validation with 422 before any hashing happens. At login, the wrong password and the unknown email produce the identical 401 message, and the dummy hash keeps the work equal in both cases. The stored record has an id, email and password_hash, and no plain password anywhere.

Further good habits

  • Never log request bodies on auth endpoints, and never return a password hash.
  • Rate-limit login attempts (see API keys and security practices).
  • Send passwords only over HTTPS.
  • Let users use long passphrases; do not force strange character rules.
  • Plan for password reset through emailed, single-use, expiring tokens, never by sending the old password.

Once users can register and log in, the next step is giving them a token to prove who they are on later requests: OAuth2 password flow and JWT.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a plain SHA-256 hash a poor choice for storing passwords?

    SHA-256 is designed for speed. Password hashes must be deliberately slow (and salted) to make guessing expensive.
  2. 2. What is the purpose of a salt?

    A random per-user salt is stored with the hash and mixed into it, so every user must be attacked separately.
  3. 3. At login the email does not exist. What should the API answer?

    Different messages reveal which emails are registered. Use one generic message (and similar timing).
  4. 4. Why use hmac.compare_digest instead of == for comparing hashes?

    == stops at the first difference, which can leak information through timing. compare_digest takes the same time either way.
  5. 5. Which library and algorithm is the usual recommendation for new FastAPI projects?

    pwdlib wraps modern algorithms; Argon2id is memory-hard and the first choice today.

Summary

  • Store a salted, deliberately slow, one-way hash, never the password and not an encrypted copy.
  • A stored hash string should carry its algorithm, cost and salt so you can verify now and upgrade later.
  • Compare with hmac.compare_digest; production code should use hashlib.pbkdf2_hmac, scrypt, or pwdlib with Argon2id.
  • Hashing is CPU-heavy: keep it off the event loop in real apps.
  • Registration validates input, returns a model without the hash and answers duplicates with 409.
  • Login uses one generic 401 for unknown users and wrong passwords.

Next: OAuth2 password flow and JWT.