Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

Storing Passwords So a Breach Is Not a Disaster

Store passwords with Argon2id and upgrade old hashes at login, then build login, logout and password reset endpoints that answer the same way for unknown accounts, throttle guessing and end sessions when they should end.

Contentsand lesson path

What you will learn

  • Store and verify passwords with an adaptive hash (Argon2id or bcrypt) and implement login, logout and password reset flows that resist account enumeration and brute force.

Prerequisites: HTTP & APIs

01. Why it matters

Passwords are attacked in two places. If your database leaks, through SQL injection, an exposed backup or an insider, attackers guess passwords offline against the stored hashes, as fast as their hardware allows, with nobody watching. While your service runs, they guess online through the login form, and they use the login and reset pages to find out which email addresses have accounts. That list (account enumeration) makes phishing and targeted guessing cheaper.

This worked example stores passwords with Argon2id, a deliberately slow hash, then builds login, logout and reset endpoints in FastAPI that answer the same way for unknown accounts, slow down guessing and end sessions when they should. Tests then attack each endpoint.

02. Choosing the hash: why Argon2id

General-purpose hashes such as SHA-256 are built to be fast. A graphics card (GPU) runs thousands of them in parallel, so an attacker with a leaked table can test a huge number of guesses per second. A per-user salt (random bytes stored next to each hash) stops attackers reusing work across users, but it does not make any single guess slower.

Password hashing functions add cost on purpose. PBKDF2 repeats a hash many times but needs almost no memory, so GPUs still run it well in parallel. bcrypt uses a small, fixed amount of memory and a cost factor. scrypt and Argon2 are memory-hard: each guess needs a large block of RAM, which limits how many guesses a GPU can run at once. Its Argon2id variant starts with memory access that does not depend on the password, which resists side-channel timing attacks, then switches to password-dependent access, which resists GPU trade-offs. OWASP and RFC 9106 recommend Argon2id. NIST SP 800-63B-4 (2025) requires passwords to be salted (at least 32 bits of salt) and hashed, and recommends a cost factor as high as practical, raised over time. It also requires at least 15 characters for a password used on its own, and forbids composition rules and forced periodic changes.

Argon2id has three cost parameters, and every hash records the values it was made with:

  • Memory (m, in KiB): RAM used per hash. OWASP's minimum is 19,456 KiB (19 MiB) with t=2 and p=1, or an equal trade such as 47,104 KiB with t=1. The code below uses 64 MiB.
  • Time (t): passes over that memory. RFC 9106 suggests t=1 with 2 GiB, or t=3 with 64 MiB when memory is tight (both with p=4).
  • Parallelism (p): lanes the memory is split into. Raising it adds no memory or passes, so it does not replace m and t.

OWASP's rule of thumb is that one hash should take less than a second. Benchmark on your own servers: every login pays this cost. A pepper, a secret key mixed in with HMAC before hashing and kept in a secrets vault, adds protection when only the database leaks.

03. Step 1: verify and upgrade hashes at login

A stored hash can only be strengthened while you have the password, which is at login. So the verify function also asks whether the hash was made with older settings, and if so returns a new hash to save. Install argon2-cffi and create password_service.py:

Python · password_service.py
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError

# Above OWASP's minimum (m=19456 KiB, t=2, p=1); benchmark on your servers
hasher = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=1)


def hash_password(plain_password: str) -> str:
    """Argon2id with a fresh random salt, encoded as a PHC string."""
    return hasher.hash(plain_password)


def verify_and_maybe_rehash(plain_password: str,
                            stored_hash: str) -> tuple[bool, str | None]:
    """Return (is_valid, new_hash_if_the_stored_one_is_outdated)."""
    try:
        hasher.verify(stored_hash, plain_password)
    except (VerificationError, InvalidHashError):
        # Wrong password (VerifyMismatchError is a VerificationError),
        # or a corrupt or non-Argon2 stored hash: a failed login, not a 500
        return False, None
    if hasher.check_needs_rehash(stored_hash):
        return True, hasher.hash(plain_password)  # save this new hash
    return True, None

The stored value is a PHC string such as $argon2id$v=19$m=65536,t=2,p=1$<salt>$<hash>. verify reads the salt and parameters from it, so old hashes keep working after you raise the settings, and check_needs_rehash returns True until that user next logs in.

The except clause catches more than a wrong password. InvalidHashError means the stored value is not an Argon2 hash at all, such as a corrupt row or a legacy bcrypt hash. When migrating from bcrypt, verify $2b$ hashes with bcrypt and rehash with Argon2id. Most bcrypt implementations use only the first 72 bytes of a password, so reject longer ones. If you pre-hash instead, use only the form the OWASP Password Storage Cheat Sheet gives, base64 of an HMAC-SHA-384 keyed with a pepper; a plain SHA-256 pre-hash is unsafe (null bytes in the digest, and password shucking with hashes leaked elsewhere).

04. Step 2: a login endpoint that does not leak

A login endpoint can leak in three ways: a different message for "no such user" and "wrong password", a different response time, and unlimited guessing. The app below fixes all three, with dictionaries instead of a database. Create login_app.py from the next four blocks, in order. The first holds the stores:

Python · login_app.py (1 of 4)
"""Login, logout and password reset that do not reveal which accounts exist."""
import hashlib
import math
import secrets
import time
from collections import defaultdict, deque

from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from fastapi import BackgroundTasks, Cookie, FastAPI, HTTPException, Request, Response
from pydantic import BaseModel

hasher = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=1)
DUMMY_HASH = hasher.hash(secrets.token_urlsafe(16))  # verified for unknown emails
USERS: dict[str, str] = {}                  # email -> Argon2id hash
SESSIONS: dict[str, str] = {}               # session ID -> email
RESETS: dict[str, tuple[str, float]] = {}   # sha256(token) -> (email, expires_at)
OUTBOX: list[tuple[str, str]] = []          # (email, raw token): stands in for email
RESET_TTL = 30 * 60
clock = time.time                           # tests replace this to move time on

Next, a small limiter. It remembers the times of recent failures for each key and answers how many seconds the caller must wait:

Python · login_app.py (2 of 4)
class FailureLimiter:
    """Allow `limit` failed attempts per key within a sliding window."""

    def __init__(self, limit: int, window: float):
        self.limit, self.window = limit, window
        self.failures: dict[str, deque[float]] = defaultdict(deque)

    def retry_after(self, key: str) -> int:
        """Seconds until this key may try again; 0 means it may try now."""
        q, now = self.failures[key], clock()
        while q and q[0] <= now - self.window:
            q.popleft()                     # forget failures older than the window
        if len(q) < self.limit:
            return 0
        return math.ceil(q[0] + self.window - now)

    def record_failure(self, key: str) -> None:
        self.failures[key].append(clock())


per_account = FailureLimiter(limit=5, window=15 * 60)
per_ip = FailureLimiter(limit=20, window=15 * 60)
app = FastAPI()
Python · login_app.py (3 of 4)
class Login(BaseModel):
    email: str
    password: str


def password_ok(email: str, password: str) -> bool:
    stored = USERS.get(email)
    try:
        # Unknown email: verify against DUMMY_HASH anyway, so both paths do
        # the same slow Argon2id work and take a similar time.
        hasher.verify(stored or DUMMY_HASH, password)
    except (VerificationError, InvalidHashError):
        return False
    return stored is not None


@app.post("/login")
def login(body: Login, request: Request, response: Response,
          session: str | None = Cookie(default=None)):
    email = body.email.strip().lower()
    acct, ip = f"acct:{email}", f"ip:{request.client.host}"
    wait = max(per_account.retry_after(acct), per_ip.retry_after(ip))
    if wait:
        raise HTTPException(429, "Too many attempts; try again later",
                            headers={"Retry-After": str(wait)})
    if not password_ok(email, body.password):
        per_account.record_failure(acct)
        per_ip.record_failure(ip)
        raise HTTPException(401, "Invalid email or password")
    per_account.failures.pop(acct, None)
    SESSIONS.pop(session or "", None)       # drop any session ID from before login
    sid = secrets.token_urlsafe(32)         # and always issue a fresh one
    SESSIONS[sid] = email
    response.set_cookie("session", sid, max_age=8 * 3600, httponly=True,
                        secure=True, samesite="lax")
    return {"detail": "Signed in"}

password_ok runs Argon2id even when the email is unknown, against DUMMY_HASH, a hash of a random value made at start-up. Without it, unknown emails would fail faster, by about one Argon2id hash, and the timing alone would reveal which accounts exist. Both failures return the same status and the same body, Invalid email or password.

The limiter counts failures per account and per client IP: 5 per account and 20 per IP in any 15 minutes. Past either limit, the endpoint answers 429 Too Many Requests with a Retry-After header saying how many seconds to wait. Unknown emails are throttled like real ones, so the 429 reveals nothing. The block is temporary on purpose: a permanent lockout lets anyone lock real users out by typing their email with wrong passwords.

Neither limit stops password spraying, where an attacker tries one common password against thousands of accounts from many IP addresses. Each account sees one failure and each IP stays under its limit. The defences that work there are rejecting common and breached passwords when users choose them (for example against the Pwned Passwords list) and offering or requiring multi-factor authentication (MFA), which OWASP calls the best defence against most password attacks.

On success, the handler discards any session ID the browser sent and always creates a new random one. Reusing an ID from before login allows session fixation: an attacker plants a known ID in the victim's browser and uses it once the victim logs in.

05. Step 3: logout and password reset

Python · login_app.py (4 of 4)
@app.get("/me")
def me(session: str | None = Cookie(default=None)):
    email = SESSIONS.get(session or "")
    if email is None:
        raise HTTPException(401, "Not signed in")
    return {"email": email}


@app.post("/logout", status_code=204)
def logout(response: Response, session: str | None = Cookie(default=None)):
    SESSIONS.pop(session or "", None)       # server side: the old ID stops working
    response.delete_cookie("session", secure=True, httponly=True, samesite="lax")

class ResetRequest(BaseModel):
    email: str


class ResetConfirm(BaseModel):
    token: str
    new_password: str


def sha256(raw: str) -> str:
    return hashlib.sha256(raw.encode()).hexdigest()


def send_reset_email(email: str) -> None:
    """Runs after the response is sent, so it cannot change the response time."""
    if email not in USERS:
        return
    raw = secrets.token_urlsafe(32)
    RESETS[sha256(raw)] = (email, clock() + RESET_TTL)  # store only the hash
    OUTBOX.append((email, raw))             # a real app emails a link with raw


@app.post("/password-reset", status_code=202)
def request_reset(body: ResetRequest, tasks: BackgroundTasks):
    tasks.add_task(send_reset_email, body.email.strip().lower())
    return {"detail": "If that email has an account, we have sent a reset link"}


@app.post("/password-reset/confirm")
def confirm_reset(body: ResetConfirm):
    entry = RESETS.pop(sha256(body.token), None)   # pop: each token works once
    if entry is None or entry[1] < clock():
        raise HTTPException(400, "Invalid or expired reset link")
    email = entry[0]
    USERS[email] = hasher.hash(body.new_password)
    for sid in [s for s, e in SESSIONS.items() if e == email]:
        del SESSIONS[sid]                   # sign every device out
    return {"detail": "Password changed; please sign in again"}

Logout deletes the session on the server. Deleting only the cookie would leave a copied cookie working until it expires.

The reset request answers 202 Accepted with the same body for every address and does the real work in a background task that runs after the response is sent, so the response time does not depend on whether the account exists. OUTBOX stands in for the mail server.

The token comes from secrets, the operating system's secure random source. The server stores only its SHA-256 hash, so a leaked table holds no working links. A fast hash is fine here, unlike for passwords, because a 32-byte random token cannot be guessed. Each token expires after 30 minutes and works once, because pop removes it as it is used. A successful reset deletes every session of that user, so an attacker who was signed in is thrown out, and it does not sign the user in. OWASP also suggests rate limiting reset requests per account and emailing the user after a change.

06. Step 4: attack it with tests

In the same folder, create a virtual environment and install the pinned packages (tested with Python 3.12.13; httpx2 is the HTTP client that current FastAPI TestClient releases use):

Shell · set up the environment
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "fastapi==0.165.0" "argon2-cffi==25.1.0" "pytest==9.2.0" "httpx2==2.16.2"

Create test_login.py. The fixture resets the stores, adds one user and replaces clock with a fake one so tests can move time forward without waiting. The client uses an https base URL because a Secure cookie is only sent over HTTPS:

Python · test_login.py (1 of 3)
import pytest
from fastapi.testclient import TestClient

import login_app as m

ANA, PW = "[email protected]", "correct horse 42"


@pytest.fixture
def client(monkeypatch):
    for store in (m.USERS, m.SESSIONS, m.RESETS, m.OUTBOX,
                  m.per_account.failures, m.per_ip.failures):
        store.clear()
    m.USERS[ANA] = m.hasher.hash(PW)
    now = [1_000_000.0]                     # a fake clock the tests can move
    monkeypatch.setattr(m, "clock", lambda: now[0])
    c = TestClient(m.app, base_url="https://testserver")  # Secure cookies need https
    c.now = now
    return c


def login(c, email, password):
    return c.post("/login", json={"email": email, "password": password})


class SpyHasher:
    """Wraps the real hasher and records which hash each login verified."""

    def __init__(self, real):
        self.real, self.checked = real, []

    def verify(self, stored_hash, password):
        self.checked.append(stored_hash)
        return self.real.verify(stored_hash, password)
Python · test_login.py (2 of 3)
def test_unknown_email_and_wrong_password_look_the_same(client, monkeypatch):
    spy = SpyHasher(m.hasher)
    monkeypatch.setattr(m, "hasher", spy)
    a = login(client, "[email protected]", "guess")
    b = login(client, ANA, "guess")
    assert (a.status_code, a.json()) == (b.status_code, b.json())
    assert a.json() == {"detail": "Invalid email or password"}
    assert spy.checked == [m.DUMMY_HASH, m.USERS[ANA]]  # Argon2id ran both times


def test_sixth_failure_on_one_account_gets_429(client):
    for _ in range(5):
        assert login(client, ANA, "guess").status_code == 401
    r = login(client, ANA, PW)              # even the right password must wait
    assert r.status_code == 429 and r.headers["Retry-After"] == "900"
    client.now[0] += 901                    # the window has passed
    assert login(client, ANA, PW).status_code == 200


def test_one_ip_spraying_many_accounts_gets_429(client):
    codes = [login(client, f"user{i}@example.com", "Summer2026!").status_code
             for i in range(21)]
    assert codes == [401] * 20 + [429]


def test_login_rotates_session_id_and_sets_cookie_flags(client):
    client.cookies.set("session", "planted-by-attacker")  # session fixation try
    r = login(client, ANA, PW)
    sid = r.cookies["session"]
    assert sid != "planted-by-attacker"
    cookie = r.headers["set-cookie"]
    for flag in ("HttpOnly", "Max-Age=28800", "SameSite=lax", "Secure"):
        assert flag in cookie


def test_logout_kills_the_session_on_the_server(client):
    sid = login(client, ANA, PW).cookies["session"]
    assert client.post("/logout").status_code == 204
    client.cookies.set("session", sid)      # replay the old cookie
    assert client.get("/me").status_code == 401
Python · test_login.py (3 of 3)
def test_reset_request_looks_the_same_for_unknown_email(client):
    a = client.post("/password-reset", json={"email": "[email protected]"})
    b = client.post("/password-reset", json={"email": ANA})
    assert (a.status_code, a.json()) == (b.status_code, b.json())
    assert a.status_code == 202 and [e for e, _ in m.OUTBOX] == [ANA]


def test_reset_token_is_hashed_single_use_and_signs_out(client):
    old_sid = login(client, ANA, PW).cookies["session"]
    client.post("/password-reset", json={"email": ANA})
    raw = m.OUTBOX[0][1]
    assert raw not in m.RESETS and m.sha256(raw) in m.RESETS
    body = {"token": raw, "new_password": "new pass 2026"}
    assert client.post("/password-reset/confirm", json=body).status_code == 200
    assert client.post("/password-reset/confirm", json=body).status_code == 400
    client.cookies.set("session", old_sid)
    assert client.get("/me").status_code == 401   # old sessions are gone


def test_expired_reset_token_is_refused(client):
    client.post("/password-reset", json={"email": ANA})
    raw = m.OUTBOX[0][1]
    client.now[0] += 31 * 60                # 31 minutes later
    body = {"token": raw, "new_password": "new pass 2026"}
    assert client.post("/password-reset/confirm", json=body).status_code == 400
Shell · run the tests
python -m pytest -v --no-header -p no:cacheprovider
Illustrative output (run time varies)
============================= test session starts ==============================
collecting ... collected 8 items

test_login.py::test_unknown_email_and_wrong_password_look_the_same PASSED [ 12%]
test_login.py::test_sixth_failure_on_one_account_gets_429 PASSED         [ 25%]
test_login.py::test_one_ip_spraying_many_accounts_gets_429 PASSED        [ 37%]
test_login.py::test_login_rotates_session_id_and_sets_cookie_flags PASSED [ 50%]
test_login.py::test_logout_kills_the_session_on_the_server PASSED        [ 62%]
test_login.py::test_reset_request_looks_the_same_for_unknown_email PASSED [ 75%]
test_login.py::test_reset_token_is_hashed_single_use_and_signs_out PASSED [ 87%]
test_login.py::test_expired_reset_token_is_refused PASSED                [100%]

============================== 8 passed in 23.71s ==============================

Each test is an attack. SpyHasher proves that the unknown-email path ran Argon2id, which is steadier than timing on a busy machine. To see the tests fail, break the app: return early in password_ok for unknown emails, or change RESETS.pop to RESETS.get.

07. Check your understanding

Practice check · 3 questions

Password storage and login flows

Three questions on legacy hashes, login timing and reset tokens.

Q1. Some rows still hold bcrypt hashes from an old system. Ana's row is `$2b$12$…`, and she types her correct password. What does `verify_and_maybe_rehash` from step 1 return?
Q2. A login handler returns the same 401 body for every failure, but it skips the hash check when the email is not in the users table. What can an attacker learn?
Q3. An attacker gets a read-only copy of your reset-token table, which holds SHA-256(token), the email and the expiry. What can they do with it?
Practice only: not graded, not saved, not evidence.

08. Apply it

In your practice API, add sign-up and login with Argon2id and the rehash check, then add the reset and logout endpoints from this lesson, backed by your database instead of dictionaries. At sign-up, reject passwords found in a breached-password list. Port the eight tests, and add one more: after five failures for one email, a sixth attempt from a different client IP still gets 429. Then tune memory_cost and time_cost on your server.

The next lesson compares server-side sessions, signed tokens and API keys, explains the cookie attributes this app sets, and verifies JWTs.

09. Review prompt

Without looking back, explain why SHA-256 with a salt is a poor password store and what memory hardness adds. Then list three ways a login or reset endpoint can reveal which accounts exist, and how this lesson closes each one. Finally, explain why throttling is temporary and why it does not stop password spraying.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check