Authentication in FastAPI: Password Hashing, OAuth2PasswordBearer, JWT, Refresh Tokens, Password Reset, API-Key Headers
"When authenticate_user is called with a username that doesn't exist in the database, we still run verify_password against a dummy hash. This ensures the endpoint takes roughly the same amount of time to respond whether the username is valid or not, preventing timing attacks that could be used to enumerate existing usernames." — FastAPI documentation, "OAuth2 with Password (and hashing), Bearer with JWT tokens", fastapi.tiangolo.com/tutorial/security/oauth2-jwt
Summary: Authentication in FastAPI is a handful of dependencies around three stores of secrets. Passwords are stored as argon2id hashes (pwdlib), with a random salt and a tunable work factor. A login endpoint reads OAuth2PasswordRequestForm, verifies the hash, and returns a short-lived signed access token (a JWT made with PyJWT, carrying sub, exp, iat, nbf, jti, aud, iss) plus a long-lived opaque refresh token that the server stores only as a SHA-256 hash. OAuth2PasswordBearer reads the Authorization header. get_current_user decodes the token with a fixed algorithm list, an audience, an issuer and a leeway for clock skew, then answers 401 with WWW-Authenticate: Bearer for every failure. Refresh tokens rotate on every use; a reused one revokes its whole family. Logout revokes the family and puts the access token's jti on a denylist. Password reset uses a hashed, expiring, single-use token sent by e-mail from BackgroundTasks, and gives the same answer for every address. Machine clients use a hashed API key in an APIKeyHeader. Settings hold the secret key as a SecretStr. Every one of those claims is a passing test in the snippet project. Focus: OAuth2PasswordBearer and tokenUrl, OAuth2PasswordRequestForm, the Authorization header and Bearer tokens, WWW-Authenticate, 401 vs 403, password hashing (argon2id, bcrypt, salt, work factor, verify and rehash, pwdlib vs passlib), JWT with PyJWT vs python-jose (and their CVE history), HS256 vs RS256 vs EdDSA, the secret key, key rotation with kid, registered claims, leeway and clock skew, token expiry, access vs refresh tokens, refresh rotation and reuse detection, token revocation, logout, the jti store and denylist, get_current_user with Depends and Security, a scopes preview (SecurityScopes), APIKeyHeader and API key hashing, cookie storage (HttpOnly, Secure, SameSite) and CSRF with a signed double submit, SecretStr and pydantic-settings, secrets.compare_digest, user enumeration and generic errors, password reset tokens (hashing, single use, expiry, e-mail via BackgroundTasks), rate limiting login and lockout, the Swagger "Authorize" button, dependency_overrides and httpx AsyncClient tests, and the Laravel (Sanctum, Passport, Fortify) and Go (golang-jwt, bcrypt) equivalents. Learning goal: Build and test the authentication layer of a FastAPI service so that no password, refresh token, reset token or API key is ever stored in clear, every token check fails closed with the right status code, a stolen refresh token is detected the moment it is replayed, nothing in the responses or their timing tells an attacker which accounts exist, and every one of these properties is pinned by a test that runs in under three seconds.
This page owns the FastAPI implementation of authentication. It links to the theory and does not re-teach it. What a JWT is, every header attack (alg, kid, jku) and every claim rule are in JWT Deep Dive. Password storage theory, MFA and server sessions are in Authentication: Passwords, MFA & Sessions. OAuth 2.0 grants, OIDC and SSO are in OAuth 2.0, OIDC & SSO. Cookies, CORS and the browser side of sessions are in Web Sessions, Cookies & CORS. Throttling algorithms are in Rate Limiting Algorithms (Go twin: Rate Limiting in Go). Roles, permissions and OAuth2 scopes in depth are in Authorization: RBAC & Scopes. Depends, caching and overrides are in Dependency Injection with Depends. Headers and cookies as parameters are in Request Validation. HTTPException and error bodies are in Exception Handling. Background work and e-mail providers are in Background Tasks, Caching & External APIs. Fixtures and the test database are in Testing FastAPI. The Go version of this chapter is Authentication in Go.
Facts below were checked against the FastAPI security tutorial (first steps, get current user, simple OAuth2, OAuth2 with JWT), the advanced security guide (OAuth2 scopes, HTTP Basic), the FastAPI security reference and release notes up to 0.165.0 (2026-11-18), the PyJWT 2.15.1 docs (usage, algorithms, API, changelog), the pwdlib README, guide, changelog and source, the argon2-cffi docs, PyPI metadata for passlib, libpass, pwdlib, PyJWT, python-jose and pydantic-settings, the GitHub advisories for python-jose (CVE-2024-33663, CVE-2024-33664) and PyJWT (CVE-2022-29217), RFC 6749, 6750, 7519, 8037, 8725, 9106, 9110 and 9700, the OWASP cheat sheets (Authentication, Session Management, Forgot Password, Password Storage, JWT, CSRF Prevention) and API Security Top 10 2023 (API2), the Python secrets, hmac and hashlib docs, the Starlette request and response docs, the Pydantic SecretStr and pydantic-settings docs, Laravel 13 (Sanctum, Passport, Fortify, hashing, password reset) and golang-jwt v5 plus golang.org/x/crypto/bcrypt source. All of them are saved under pipeline/sources/fastapi-authentication-jwt/. The page is written for Python 3.12+ and current releases. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, with the newest releases that still install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, pydantic-settings 2.9.1, SQLAlchemy 2.0.58, pwdlib 0.2.1 (with argon2-cffi 23.1.0 and bcrypt 4.3.0), PyJWT 2.15.1 with cryptography 50.0.2, python-multipart 0.0.20, Uvicorn 0.39.0, httpx 0.28.1, pytest 8.4.2 and anyio 4.12.1. On Python 3.11+ use pwdlib 0.4.x and pydantic-settings 2.16.x; the APIs used here are the same. Every status code, header, error text and timing quoted as "real" is what those runs printed (pipeline/sources/fastapi-authentication-jwt/runs/).
Page map
| If you are looking for | Go to |
|---|---|
| The tables to memorise | Everything in one minute |
| Why not just check a password per request | Why it exists |
| RFC 6749 (2012) to pwdlib in the FastAPI docs (2025) | Where it comes from |
| A before/after auth service | Python |
OAuth2PasswordBearer, tokenUrl, Swagger Authorize | OAuth2PasswordBearer |
| The login form | OAuth2PasswordRequestForm |
401, 403 and WWW-Authenticate | Status codes |
| argon2id, bcrypt, salt, work factor | Password hashing |
| pwdlib vs passlib, verify and rehash | pwdlib |
| PyJWT vs python-jose | Choosing a JWT library |
Claims, exp, nbf, aud, iss, leeway | Access tokens and claims |
HS256, RS256, EdDSA, kid, key rotation | Algorithms and keys |
get_current_user | The current-user dependency |
| Refresh tokens, rotation, reuse detection | Refresh tokens |
Logout, denylist, jti store | Revocation and logout |
Cookies, HttpOnly, SameSite, CSRF | Cookie storage and CSRF |
SecretStr, pydantic-settings | Secrets in settings |
| Same error for unknown users, timing | User enumeration |
| Brute force, lockout, rate limiting login | Rate limiting login and lockout |
| Forgot password | Password reset |
| Machine clients | API keys |
Roles and SecurityScopes | Roles and scopes preview |
dependency_overrides, AsyncClient | Testing auth |
| Request flow, state machine, exact errors | Mechanics |
| Bugs and fixes | Solving the classic problems |
| JWT or opaque, cookie or header, HS256 or EdDSA | Choosing |
| Monolith to distributed | In architecture |
| Run it yourself | Lab |
| Sanctum, Passport, Fortify | For PHP/Laravel developers |
| golang-jwt, x/crypto/bcrypt | The Go angle |
Everything in one minute
The vocabulary. Each row is unpacked in the concept catalogue.
| Term | What it is | Plain words | In the snippet |
|---|---|---|---|
| Password hash | A slow, salted, one-way function of the password | "Store a fingerprint you cannot reverse" | users.password_hash, $argon2id$… |
| Salt | Random bytes mixed into each hash | "Same password, different hash" | 16 bytes, inside the hash string |
| Work factor | The tunable cost of one hash | "How slow, on purpose" | argon2id m=65536,t=3,p=4 |
| Access token | Short-lived credential sent on every request | "Day pass" | JWT, 15 minutes |
| Refresh token | Long-lived credential that buys new access tokens | "Renewal voucher" | rt_…, 14 days, stored as SHA-256 |
| Bearer token | Whoever holds it is allowed in | "Cash, not a cheque" | Authorization: Bearer <jwt> |
| JWT | Signed JSON: header.payload.signature | "A tamper-evident note" | create_access_token |
| Claims | The JSON fields of a JWT | "What the note says" | iss aud sub iat nbf exp jti role typ |
| Rotation | Every refresh returns a new refresh token | "One voucher, one use" | /auth/refresh |
| Reuse detection | A used refresh token coming back revokes its family | "A copied voucher burns the book" | Refresh token reuse detected |
| Denylist | Revoked jti values until their exp | "Cancelled passes" | revoked_access_tokens |
| API key | A long-lived secret for a machine | "A service badge" | X-API-Key: ak_….…, stored hashed |
| Reset token | One-time secret mailed to the user | "A one-use key in the post" | password_reset_tokens |
Status codes and headers.
| Situation | Status | Header | Body in the snippet |
|---|---|---|---|
No Authorization header | 401 | WWW-Authenticate: Bearer | {"detail":"Not authenticated"} |
Bad signature, wrong aud/iss, alg: none, revoked jti | 401 | WWW-Authenticate: Bearer | {"detail":"Could not validate credentials"} |
| Expired access token | 401 | WWW-Authenticate: Bearer | {"detail":"Token expired"} |
| Wrong password, unknown user, locked account | 401 | WWW-Authenticate: Bearer | {"detail":"Incorrect email or password"} |
| Authenticated, wrong role | 403 | none | {"detail":"Forbidden"} |
| Reused refresh token | 401 | WWW-Authenticate: Bearer | {"detail":"Refresh token reuse detected"} |
| Cookie refresh without a valid CSRF header | 403 | none | {"detail":"CSRF check failed"} |
| Bad API key | 401 | WWW-Authenticate: APIKey | {"detail":"Invalid API key"} |
| Reset requested (any e-mail) | 202 | none | If that address is registered, a reset link has been sent. |
| Reset token reused or expired | 400 | none | {"detail":"Invalid or expired reset token"} |
Lifetimes and storage.
| Secret | Lifetime here | Stored server-side as | Client keeps it in |
|---|---|---|---|
| Password | Until changed | argon2id hash | Nowhere (typed) |
| Access token | 900 s | Nothing (stateless), jti only if revoked | Memory, Authorization header |
| Refresh token | 14 days, single use | SHA-256 hash + family id | Secure storage, or an HttpOnly cookie |
| Reset token | 900 s, single use | SHA-256 hash | The e-mail link |
| API key | Until revoked | Prefix + SHA-256 hash | The machine's secret store |
| Signing secret key | Until rotated | SecretStr from the environment | Never leaves the server |
Libraries.
| Job | Use | Avoid | Why |
|---|---|---|---|
| Hash passwords | pwdlib[argon2] (FastAPI docs since 0.118.0) | original passlib 1.7.4 | passlib 1.7.4 is from 2020 and broken by Python 3.13; see pwdlib |
| Sign and verify JWTs | PyJWT (FastAPI docs since 0.111.1) | python-jose < 3.4.0 | Two 2024 CVEs; years without a release; see JWT libraries |
| Random tokens | secrets.token_urlsafe(32) | random, uuid4 as a secret | secrets is the CSPRNG API |
| Compare secrets | secrets.compare_digest | == | Constant time |
| Settings | pydantic-settings + SecretStr | Constants in code | Hidden in repr, read from env |
Why it exists
HTTP is stateless: every request must prove who sent it. Sending the password on every request (HTTP Basic) means every endpoint does a slow hash check and every log line, proxy and browser cache is one mistake away from holding the password. A token splits the problem. The password is checked once, slowly, at login. After that the client shows a token that the server can check quickly: a JWT by its signature, an opaque token by a lookup.
That split creates new problems, and the rest of this page is their fixes. A token that never expires is a password that cannot be changed, so access tokens expire after minutes. Users should not log in every 15 minutes, so a refresh token buys new access tokens. A refresh token that lives for weeks is worth stealing, so it is single use: it rotates, and a replay is detected. A signed token cannot be "un-signed", so logout needs a revocation list or short lifetimes. Login and reset forms leak which e-mails exist, so they answer the same way every time. Machines cannot type passwords, so they get API keys. Each of those secrets must be stored so that a database dump does not hand them to the attacker.
Analogy. A hotel. The passport check at the front desk is the password: slow, done once. The key card is the access token: quick to check at every door, and it stops working at checkout. The booking reference is the refresh token: it gets you a new key card, but only once, and if two people show up with the same reference, the hotel cancels the booking and calls you. The safe-deposit box code sent to your phone is the reset token.
Three common misunderstandings, up front
- "JWTs are encrypted." A JWS is only signed. Anyone can base64-decode the payload; the lab prints its claims. Never put secrets in it.
- "Logout deletes the token." The client forgets it; a copy still works until
expunless the server keeps a denylist. The snippet does both. - "OAuth2PasswordBearer checks the token." It only reads the
Authorizationheader and returns the string. Verifying it is yourget_current_user.
Where it comes from
| Year | Event | Why it matters here |
|---|---|---|
| 1999 | bcrypt (Provos and Mazières, USENIX 1999, as cited by Go's x/crypto/bcrypt) | Adaptive cost; still the Laravel default and the Go standard choice |
| 2012 | RFC 6749 (OAuth 2.0) and RFC 6750 (Bearer tokens) | The password grant, refresh tokens, WWW-Authenticate: Bearer, invalid_token / insufficient_scope |
| 2015 | RFC 7519 (JWT); Argon2 wins the Password Hashing Competition | Registered claims; the algorithm OWASP lists first |
| 2017 | RFC 8037 (January) | EdDSA (Ed25519) for JOSE |
| 2019 | PEP 594 created: deprecate crypt in 3.11, remove it in 3.13 | passlib imports crypt |
| 2020 | RFC 8725 (JWT BCP, February); passlib 1.7.4, its last original release (October); FastAPI docs switch to python-jose (0.59.0) | "Perform algorithm verification" |
| 2021 | RFC 9106 (Argon2) | The parameter profiles argon2-cffi uses as defaults |
| 2022 | PyJWT CVE-2022-29217, fixed in 2.4.0 | Key confusion through public key formats |
| 2024 | python-jose CVE-2024-33663 and CVE-2024-33664; FastAPI docs switch to PyJWT (0.111.1, July) | Choose PyJWT |
| 2025 | RFC 9700 (OAuth 2.0 Security BCP, January); python-jose 3.4.0 fixes the CVEs (February); FastAPI docs switch to pwdlib + argon2 (0.118.0, September); FastAPI security classes return 401, not 403, when credentials are missing (0.122.0, November) | Refresh rotation is a MUST-option for public clients; ROPC "MUST NOT be used" |
| 2026 | PyJWT 2.15.1 (September); pwdlib 0.4.x needs Python 3.11 (November); the libpass fork publishes as passlib 1.9.5 again (November 23) | The current pins |
Timeline of one session in this chapter's snippet
1 T+0 s POST /auth/token argon2id verify (~24 ms) -> access JWT (exp T+900) + RT1 (exp T+14 d)
2 T+60 s GET /users/me HMAC verify, no hashing -> 200
3 T+905 s GET /users/me exp passed, leeway 30 s -> still 200
4 T+931 s GET /users/me exp + leeway passed -> 401 "Token expired"
5 T+931 s POST /auth/refresh RT1 RT1 claimed, RT2 issued -> 200 new access JWT + RT2
6 T+2 h POST /auth/refresh RT1 (a stolen copy) -> 401 reuse detected, family revoked
7 T+2 h POST /auth/refresh RT2 family revoked -> 401: the user logs in againPython
Before
The auth code that ships when nobody reviews it: a hard-coded secret, an unsalted SHA-256 "password hash", a 404 for unknown users, a JWT without exp, aud or jti, and a /me route that decodes the token without checking the signature.
"""BEFORE: the auth code that ships when nobody reviews it. Every line here is a finding.
tests/test_settings_before.py proves flaws 2, 3, 5, 6 and 7; 1 and 4 are review findings
(a committed secret, a timing leak) that a unit test cannot show. Do not copy."""
import hashlib
from typing import Dict
import jwt
from fastapi import FastAPI, Form, Header, HTTPException
SECRET = "secret" # 1. hard-coded, short, committed to git
USERS: Dict[str, str] = {} # email -> sha256(password): 2. fast, unsalted hash
app = FastAPI()
@app.post("/signup")
def signup(email: str = Form(), password: str = Form()):
USERS[email] = hashlib.sha256(password.encode()).hexdigest()
return {"ok": True}
@app.post("/login")
def login(email: str = Form(), password: str = Form()):
if email not in USERS:
raise HTTPException(404, "No such user") # 3. user enumeration
if USERS[email] != hashlib.sha256(password.encode()).hexdigest(): # 4. == is not constant time
raise HTTPException(401, "Wrong password")
# 5. no exp, no aud, no iss, no jti: valid forever, revocable never
return {"token": jwt.encode({"sub": email}, SECRET, algorithm="HS256")}
@app.get("/me")
def me(authorization: str = Header()):
token = authorization.removeprefix("Bearer ") if hasattr(str, "removeprefix") else authorization[7:]
# 6. signature not verified: anyone can mint a token for anyone
claims = jwt.decode(token, options={"verify_signature": False})
# 7. a missing header is a 422 (a malformed token a 500), never 401 + WWW-Authenticate
return {"email": claims["sub"]}The tests prove five of the seven findings (real run): the login leaks which users exist (404 vs 401), the stored value is sha256("pw"), a token signed with an attacker's key is accepted, the token has no exp, and a missing header is a 422 while a malformed token is a 500. PyJWT itself warns about the short keys: InsecureKeyLengthWarning: The HMAC key is 6 bytes long, which is below the minimum recommended length of 32 bytes for SHA256. See RFC 7518 Section 3.2. (added in PyJWT 2.11.0).
import hashlib
import jwt
import pytest
from fastapi.testclient import TestClient
from pydantic import ValidationError
from app import before
from app.settings import Settings
def test_secret_is_hidden_in_repr_and_dump():
s = Settings(jwt_secret="s" * 40, _env_file=None)
assert "s" * 40 not in repr(s)
assert str(s.jwt_secret) == "**********"
assert s.model_dump()["jwt_secret"].get_secret_value() == "s" * 40
def test_missing_or_short_secret_refuses_to_start(monkeypatch):
monkeypatch.delenv("AUTH_JWT_SECRET", raising=False)
with pytest.raises(ValidationError):
Settings(_env_file=None)
with pytest.raises(ValidationError):
Settings(jwt_secret="short", _env_file=None)
def test_secret_read_from_environment(monkeypatch):
monkeypatch.setenv("AUTH_JWT_SECRET", "e" * 40)
assert Settings(_env_file=None).jwt_secret.get_secret_value() == "e" * 40
@pytest.fixture
def bc():
before.USERS.clear()
with TestClient(before.app, raise_server_exceptions=False) as c:
c.post("/signup", data={"email": "a@example.test", "password": "pw"})
yield c
def test_before_leaks_which_users_exist(bc):
assert bc.post("/login", data={"email": "x@example.test", "password": "pw"}).status_code == 404
assert bc.post("/login", data={"email": "a@example.test", "password": "no"}).status_code == 401
def test_before_stores_an_unsalted_fast_hash(bc):
assert before.USERS["a@example.test"] == hashlib.sha256(b"pw").hexdigest()
def test_before_accepts_a_token_nobody_signed(bc):
forged = jwt.encode({"sub": "admin@example.test"}, "attacker-key", algorithm="HS256")
assert bc.get("/me", headers={"Authorization": f"Bearer {forged}"}).json() == {"email": "admin@example.test"}
def test_before_tokens_never_expire(bc):
token = bc.post("/login", data={"email": "a@example.test", "password": "pw"}).json()["token"]
assert "exp" not in jwt.decode(token, options={"verify_signature": False})
def test_before_missing_header_is_422_not_401(bc):
r = bc.get("/me")
assert r.status_code == 422 and "www-authenticate" not in r.headers
def test_before_malformed_token_is_a_500(bc):
assert bc.get("/me", headers={"Authorization": "Bearer not-a-jwt"}).status_code == 500
def test_in_memory_sqlite_is_refused():
from app.db import make_engine
with pytest.raises(ValueError, match="not :memory:"):
make_engine("sqlite+pysqlite:///:memory:")After
Settings first. The secret key has no default and a 32-character minimum, so the app refuses to start without a real one. It is a SecretStr, so repr(settings) prints **********:
"""Settings: every secret is a SecretStr, read from the environment (prefix AUTH_) or .env."""
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="AUTH_", env_file=".env", extra="ignore")
# No default: the app refuses to start without a secret. SecretStr hides it in repr/logs.
jwt_secret: SecretStr = Field(min_length=32)
jwt_algorithm: str = "HS256"
jwt_issuer: str = "https://auth.example.test"
jwt_audience: str = "notes-api"
access_ttl_seconds: int = 15 * 60
refresh_ttl_seconds: int = 14 * 24 * 3600
reset_ttl_seconds: int = 15 * 60
leeway_seconds: int = 30
max_failed_logins: int = 5
database_url: str = "sqlite+pysqlite:///./auth-demo.db"
# Cookie mode for browser clients: refresh token in an HttpOnly cookie + CSRF double submit.
cookie_secure: bool = TrueThe .env.example that ships with the project. Its placeholder is too short on purpose, so a copied file fails validation instead of running on a public secret:
# Copy to .env and replace every value. Never commit the real .env.
# Generate a signing secret with: python -c "import secrets; print(secrets.token_urlsafe(64))"
# The placeholder is deliberately too short (< 32 chars): Settings() refuses to start with it.
AUTH_JWT_SECRET=CHANGE-ME
AUTH_JWT_ISSUER=https://auth.example.test
AUTH_JWT_AUDIENCE=notes-api
AUTH_ACCESS_TTL_SECONDS=900
AUTH_REFRESH_TTL_SECONDS=1209600
AUTH_RESET_TTL_SECONDS=900
AUTH_LEEWAY_SECONDS=30
AUTH_DATABASE_URL=sqlite+pysqlite:///./auth-demo.dbThe tables. Refresh tokens, reset tokens and API keys are stored as SHA-256 hashes. Refresh tokens carry a family_id, one per login, so reuse detection can revoke one device without touching the others:
"""SQLAlchemy 2 models: users, refresh tokens (hashed, with a family for reuse detection),
password-reset tokens (hashed, single use), API keys (hashed) and a jti denylist."""
from datetime import datetime
from typing import Optional
from sqlalchemy import ForeignKey, String, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(320), unique=True, index=True)
password_hash: Mapped[str] = mapped_column(String(255))
role: Mapped[str] = mapped_column(String(20), default="user")
is_active: Mapped[bool] = mapped_column(default=True)
failed_logins: Mapped[int] = mapped_column(default=0)
# Copied into every access token as "ver"; a password reset increments it, so every access
# token issued before the reset fails, even one issued in the same second.
token_version: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime]
class RefreshToken(Base):
__tablename__ = "refresh_tokens"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
# SHA-256 of the opaque token. The raw token exists only in the client's hands.
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
family_id: Mapped[str] = mapped_column(String(32), index=True)
issued_at: Mapped[datetime]
expires_at: Mapped[datetime]
used_at: Mapped[Optional[datetime]] = mapped_column(default=None)
revoked_at: Mapped[Optional[datetime]] = mapped_column(default=None)
class PasswordResetToken(Base):
__tablename__ = "password_reset_tokens"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
expires_at: Mapped[datetime]
used_at: Mapped[Optional[datetime]] = mapped_column(default=None)
class ApiKey(Base):
__tablename__ = "api_keys"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
# The first characters are stored in clear so a key can be found and shown ("ak_3f9c…").
prefix: Mapped[str] = mapped_column(String(16), unique=True)
key_hash: Mapped[str] = mapped_column(String(64))
revoked_at: Mapped[Optional[datetime]] = mapped_column(default=None)
class RevokedAccessToken(Base):
"""The jti store: access tokens revoked before their exp (logout).
expires_at = exp + leeway: decode still accepts the token during the leeway, so the row must
outlive it. purge_denylist() deletes only rows past that point."""
__tablename__ = "revoked_access_tokens"
jti: Mapped[str] = mapped_column(String(64), primary_key=True)
expires_at: Mapped[datetime]
def make_engine(url: str) -> Engine:
"""A file database (or Postgres): every Session gets its own connection and transaction.
Never StaticPool/:memory: here: one shared connection lets one request's rollback undo
another request's single-use claim."""
if url.startswith("sqlite") and ":memory:" in url:
raise ValueError("use a file SQLite database or Postgres, not :memory:")
if url.startswith("sqlite"):
# timeout: a second writer waits for the first to commit instead of failing at once.
return create_engine(url, connect_args={"check_same_thread": False, "timeout": 5})
return create_engine(url)
def purge_denylist(session, now: datetime) -> int:
from sqlalchemy import delete
result = session.execute(delete(RevokedAccessToken).where(RevokedAccessToken.expires_at < now))
return result.rowcountHashing and tokens. PasswordHash((Argon2Hasher(), BcryptHasher())) hashes new passwords with argon2id and still verifies old bcrypt hashes. verify_password runs one full verification even for an unknown user. decode_access_token fixes the algorithm list and requires every claim:
"""Password hashing (pwdlib, argon2id first, bcrypt for legacy hashes), JWT access tokens (PyJWT)
and opaque random tokens that are stored only as SHA-256 hashes."""
import hashlib
import secrets
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional
import jwt
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher
from .settings import Settings
# The first hasher hashes new passwords; every hasher in the tuple can verify.
# verify_and_update() returns a new argon2id hash when a bcrypt (or weaker argon2) hash verifies.
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher()))
# Verified when the e-mail is unknown, so an unknown user costs the same argon2 work as a wrong
# password and the response time does not reveal which e-mails exist.
DUMMY_HASH = password_hash.hash("dummy-password-for-timing-equalisation")
def hash_password(plain: str) -> str:
return password_hash.hash(plain)
def verify_password(plain: str, stored_hash: Optional[str]):
"""Return (ok, new_hash_or_None). Always runs one full hash verification."""
if stored_hash is None:
password_hash.verify(plain, DUMMY_HASH)
return False, None
return password_hash.verify_and_update(plain, stored_hash)
def utcnow() -> datetime:
return datetime.now(timezone.utc)
def create_access_token(
settings: Settings, *, subject: str, role: str, version: int = 0, now: Optional[datetime] = None
) -> str:
now = now or utcnow()
claims: Dict[str, Any] = {
"iss": settings.jwt_issuer,
"aud": settings.jwt_audience,
"sub": subject, # RFC 7519: a string; PyJWT >= 2.10 rejects a non-string sub
"iat": now,
"nbf": now,
"exp": now + timedelta(seconds=settings.access_ttl_seconds),
"jti": uuid.uuid4().hex,
"role": role, # a preview of authorization claims; checked by require_role()
"typ": "access",
"ver": version, # users.token_version at issue time; a reset increments it
}
return jwt.encode(
claims, settings.jwt_secret.get_secret_value(), algorithm=settings.jwt_algorithm
)
def decode_access_token(settings: Settings, token: str) -> Dict[str, Any]:
"""Raise jwt.InvalidTokenError (or a subclass) on any problem."""
claims = jwt.decode(
token,
settings.jwt_secret.get_secret_value(),
# A fixed list, never taken from the token header: blocks alg=none and alg confusion.
algorithms=[settings.jwt_algorithm],
audience=settings.jwt_audience,
issuer=settings.jwt_issuer,
leeway=settings.leeway_seconds,
options={"require": ["exp", "iat", "nbf", "sub", "jti", "iss", "aud", "ver"]},
)
if claims.get("typ") != "access":
raise jwt.InvalidTokenError("not an access token")
return claims
def new_opaque_token(prefix: str = "") -> str:
"""256 bits from the OS CSPRNG, URL-safe."""
return prefix + secrets.token_urlsafe(32)
def sha256_hex(token: str) -> str:
# A fast hash is right here: the input is 256 random bits, not a guessable password.
return hashlib.sha256(token.encode()).hexdigest()
def constant_time_equal(a: str, b: str) -> bool:
return secrets.compare_digest(a.encode(), b.encode())The dependencies: OAuth2PasswordBearer(tokenUrl="auth/token"), get_current_claims (decode, denylist), get_current_user (integer sub, active, token_version), require_role (403), and get_api_client with Security(APIKeyHeader(...)). As in the Depends chapter, the module has no from __future__ import annotations:
"""Dependencies. Deliberately no `from __future__ import annotations` (it breaks class dependencies)."""
from datetime import datetime, timezone
from typing import Annotated, Callable, Iterator, Optional
import jwt
from fastapi import Depends, HTTPException, Request, Security, status
from fastapi.security import APIKeyHeader, OAuth2PasswordBearer
from sqlalchemy import select
from sqlalchemy.orm import Session
from .db import ApiKey, RevokedAccessToken, User
from .mailer import Outbox
from .security import constant_time_equal, decode_access_token, sha256_hex, utcnow
from .settings import Settings
# tokenUrl is relative, as in the FastAPI tutorial: it is what Swagger UI's "Authorize" posts to.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
# auto_error=False: we raise our own 401 so the body and header are the same for every failure.
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def get_settings(request: Request) -> Settings:
return request.app.state.settings
def get_session(request: Request) -> Iterator[Session]:
with Session(request.app.state.engine) as session:
yield session
def get_clock() -> Callable[[], datetime]:
return utcnow
def get_outbox(request: Request) -> Outbox:
return request.app.state.outbox
SettingsDep = Annotated[Settings, Depends(get_settings)]
SessionDep = Annotated[Session, Depends(get_session)]
ClockDep = Annotated[Callable[[], datetime], Depends(get_clock)]
OutboxDep = Annotated[Outbox, Depends(get_outbox)]
def naive_utc(dt: datetime) -> datetime:
"""SQLite stores naive datetimes; keep everything in naive UTC inside the database."""
return dt.astimezone(timezone.utc).replace(tzinfo=None) if dt.tzinfo else dt
def credentials_error(detail: str = "Could not validate credentials") -> HTTPException:
# RFC 6750 section 3: a 401 for a bearer-protected resource carries WWW-Authenticate.
return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=detail,
headers={"WWW-Authenticate": "Bearer"},
)
def get_current_claims(
token: Annotated[str, Depends(oauth2_scheme)], settings: SettingsDep, session: SessionDep
) -> dict:
try:
claims = decode_access_token(settings, token)
except jwt.ExpiredSignatureError:
# Same status, a hint the client may use to refresh. Never echo the exception text.
raise credentials_error("Token expired")
except jwt.InvalidTokenError:
raise credentials_error()
if session.get(RevokedAccessToken, claims["jti"]) is not None:
raise credentials_error()
return claims
def get_current_user(
claims: Annotated[dict, Depends(get_current_claims)], session: SessionDep
) -> User:
try:
user_id = int(claims["sub"]) # PyJWT checks sub is a string, not that it is our id format
except ValueError:
raise credentials_error()
user = session.get(User, user_id)
if user is None or not user.is_active:
raise credentials_error()
if claims["ver"] != user.token_version: # a password reset happened after this token
raise credentials_error()
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
def require_role(role: str):
"""Authorization preview: authenticated (401 otherwise) AND allowed (403 otherwise)."""
def checker(user: CurrentUser) -> User:
if user.role != role:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
return user
return checker
def get_api_client(
api_key: Annotated[Optional[str], Security(api_key_header)], session: SessionDep
) -> ApiKey:
error = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key",
headers={"WWW-Authenticate": "APIKey"},
)
if not api_key or "." not in api_key:
raise error
prefix, _secret = api_key.split(".", 1)
row = session.scalar(select(ApiKey).where(ApiKey.prefix == prefix))
# Compare the full-key hash in constant time; a missing row still does one comparison.
expected = row.key_hash if row is not None else "0" * 64
if not constant_time_equal(sha256_hex(api_key), expected) or row is None or row.revoked_at:
raise error
return rowThe routes: signup, login, refresh with rotation and reuse detection, logout, the two password-reset steps, /users/me, an admin router guarded once for all its routes, API-key creation and a machine route. claim_once is the atomic single-use step:
"""The auth service: signup, login (OAuth2 password flow), refresh rotation with reuse detection,
logout, password reset, API keys for machine clients, and protected routes."""
import hashlib
import hmac
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from typing import Annotated, Optional
from fastapi import (
APIRouter, BackgroundTasks, Body, Cookie, Depends, FastAPI, Header, HTTPException,
Request, Response, status,
)
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel, Field
from sqlalchemy import select, update
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session
from .db import ApiKey, Base, PasswordResetToken, RefreshToken, RevokedAccessToken, User, make_engine
from .deps import (
ClockDep, CurrentUser, OutboxDep, SessionDep, SettingsDep, credentials_error,
get_api_client, get_current_claims, naive_utc, require_role,
)
from .mailer import Outbox
from .security import (
constant_time_equal, create_access_token, hash_password, new_opaque_token, sha256_hex,
verify_password,
)
from .settings import Settings
GENERIC_LOGIN_ERROR = "Incorrect email or password"
MAX_PASSWORD_LENGTH = 128 # the same bound as signup/reset: no megabyte "passwords" reach argon2
RESET_ACCEPTED = {"detail": "If that address is registered, a reset link has been sent."}
REFRESH_COOKIE = "refresh_token"
CSRF_COOKIE = "csrf_token"
class SignupIn(BaseModel):
email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$", max_length=320)
# OWASP Authentication Cheat Sheet: >= 15 characters without MFA, allow >= 64, no composition rules.
password: str = Field(min_length=15, max_length=MAX_PASSWORD_LENGTH)
class UserOut(BaseModel):
id: int
email: str
role: str
class TokenPair(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
refresh_token: Optional[str] = None
class RefreshIn(BaseModel):
refresh_token: str
class ResetRequestIn(BaseModel):
email: str
class ResetConfirmIn(BaseModel):
token: str
new_password: str = Field(min_length=15, max_length=MAX_PASSWORD_LENGTH)
def issue_refresh(session, user_id: int, family_id: str, now, settings: Settings) -> str:
raw = new_opaque_token("rt_")
session.add(RefreshToken(
user_id=user_id, token_hash=sha256_hex(raw), family_id=family_id,
issued_at=naive_utc(now), expires_at=naive_utc(now + timedelta(seconds=settings.refresh_ttl_seconds)),
))
return raw
def claim_once(session, model, row_id: int, now) -> bool:
"""Atomic single use: only one concurrent request can flip used_at from NULL.
A read-then-set (`if row.used_at is None: row.used_at = now`) lets two racing requests both win."""
conditions = [model.id == row_id, model.used_at.is_(None)]
if hasattr(model, "revoked_at"):
conditions.append(model.revoked_at.is_(None))
result = session.execute(update(model).where(*conditions).values(used_at=naive_utc(now)))
return result.rowcount == 1
def revoke_family(session, family_id: str, now) -> None:
session.execute(
update(RefreshToken)
.where(RefreshToken.family_id == family_id, RefreshToken.revoked_at.is_(None))
.values(revoked_at=naive_utc(now))
)
def token_pair(settings: Settings, user: User, refresh: str, now, cookie_mode: bool, response: Response) -> TokenPair:
access = create_access_token(
settings, subject=str(user.id), role=user.role, version=user.token_version, now=now
)
if cookie_mode:
# Browser clients: the refresh token never touches JavaScript.
response.set_cookie(
REFRESH_COOKIE, refresh, max_age=settings.refresh_ttl_seconds, path="/auth",
httponly=True, secure=settings.cookie_secure, samesite="strict",
)
# Signed double-submit CSRF token bound to this refresh token: readable by JS
# (not HttpOnly), echoed in X-CSRF-Token, verified by HMAC on the server.
response.set_cookie(
CSRF_COOKIE, csrf_token_for(settings, refresh), max_age=settings.refresh_ttl_seconds, path="/",
httponly=False, secure=settings.cookie_secure, samesite="strict",
)
return TokenPair(access_token=access, expires_in=settings.access_ttl_seconds)
return TokenPair(access_token=access, expires_in=settings.access_ttl_seconds, refresh_token=refresh)
def _csrf_mac(settings: Settings, refresh_token: str, nonce: str) -> str:
bound = sha256_hex(refresh_token)
# Length-prefixed fields: an unambiguous encoding, as the OWASP CSRF cheat sheet asks.
msg = f"{len(bound)}:{bound}|{len(nonce)}:{nonce}".encode()
return hmac.new(settings.jwt_secret.get_secret_value().encode(), msg, hashlib.sha256).hexdigest()
def csrf_token_for(settings: Settings, refresh_token: str) -> str:
nonce = new_opaque_token()
return f"{nonce}.{_csrf_mac(settings, refresh_token, nonce)}"
def csrf_ok(settings: Settings, refresh_token: str, header_value: Optional[str]) -> bool:
# Read the token from the header (never from the cookie alone) and recompute the HMAC
# against the refresh cookie: a cookie planted by a sibling subdomain cannot match.
if not header_value or header_value.count(".") != 1:
return False
nonce, mac = header_value.split(".")
return constant_time_equal(mac, _csrf_mac(settings, refresh_token, nonce))
auth = APIRouter(prefix="/auth", tags=["auth"])
@auth.post("/signup", status_code=status.HTTP_201_CREATED, response_model=UserOut)
def signup(body: SignupIn, session: SessionDep, clock: ClockDep):
email = body.email.strip().lower()
if session.scalar(select(User).where(User.email == email)) is not None:
# Signup is the one place enumeration is hard to avoid; production sends a mail instead.
raise HTTPException(status.HTTP_409_CONFLICT, "Email already registered")
user = User(email=email, password_hash=hash_password(body.password), created_at=naive_utc(clock()))
session.add(user)
session.commit()
return UserOut(id=user.id, email=user.email, role=user.role)
@auth.post("/token", response_model=TokenPair, response_model_exclude_none=True)
def login(
form: Annotated[OAuth2PasswordRequestForm, Depends()],
response: Response,
session: SessionDep,
settings: SettingsDep,
clock: ClockDep,
x_client: Annotated[Optional[str], Header()] = None,
):
# OAuth2 calls the field "username"; we put the e-mail in it.
user = session.scalar(select(User).where(User.email == form.username.strip().lower()))
if len(form.password) > MAX_PASSWORD_LENGTH:
# OAuth2PasswordRequestForm has no length limit of its own. Reject before hashing, with
# the same generic answer (this branch depends only on the input, not on the account).
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, GENERIC_LOGIN_ERROR, headers={"WWW-Authenticate": "Bearer"}
)
ok, new_hash = verify_password(form.password, user.password_hash if user else None)
# Lockout after N failures. A locked account gets the SAME generic 401 (after the same hash
# work), so the lockout itself does not reveal that the e-mail exists. Reset unlocks it.
locked = user is not None and user.failed_logins >= settings.max_failed_logins
if not ok or user is None or not user.is_active or locked:
if user is not None:
# Increment in SQL, not in Python: concurrent failures must all count.
session.execute(
update(User).where(User.id == user.id).values(failed_logins=User.failed_logins + 1)
)
session.commit()
raise HTTPException(
status.HTTP_401_UNAUTHORIZED, GENERIC_LOGIN_ERROR, headers={"WWW-Authenticate": "Bearer"}
)
if new_hash is not None: # verify and rehash: bcrypt or old argon2 parameters -> current argon2id
user.password_hash = new_hash
user.failed_logins = 0
now = clock()
refresh = issue_refresh(session, user.id, uuid.uuid4().hex, now, settings)
session.commit()
return token_pair(settings, user, refresh, now, x_client == "browser", response)
@auth.post("/refresh", response_model=TokenPair, response_model_exclude_none=True)
def refresh(
response: Response,
session: SessionDep,
settings: SettingsDep,
clock: ClockDep,
body: Annotated[Optional[RefreshIn], Body()] = None,
refresh_cookie: Annotated[Optional[str], Cookie(alias=REFRESH_COOKIE)] = None,
x_csrf_token: Annotated[Optional[str], Header()] = None,
):
cookie_mode = body is None and refresh_cookie is not None
if cookie_mode:
# A cookie is sent automatically by the browser, so prove the caller can read our cookie.
if not csrf_ok(settings, refresh_cookie, x_csrf_token):
raise HTTPException(status.HTTP_403_FORBIDDEN, "CSRF check failed")
raw = refresh_cookie
elif body is not None:
raw = body.refresh_token
else:
raise credentials_error()
now = clock()
row = session.scalar(select(RefreshToken).where(RefreshToken.token_hash == sha256_hex(raw)))
if row is None:
raise credentials_error()
if row.used_at is not None or row.revoked_at is not None:
# Reuse detection: a rotated (or revoked) token came back. Either the client or an
# attacker holds a stolen copy; we cannot tell which, so the whole family dies.
revoke_family(session, row.family_id, now)
session.commit()
raise credentials_error("Refresh token reuse detected")
if row.expires_at <= naive_utc(now):
raise credentials_error("Refresh token expired")
user = session.get(User, row.user_id)
if user is None or not user.is_active:
raise credentials_error()
if not claim_once(session, RefreshToken, row.id, now): # rotation: single use, atomically
# Lost the race against a concurrent refresh with the same token: that is reuse too.
revoke_family(session, row.family_id, now)
session.commit()
raise credentials_error("Refresh token reuse detected")
new_raw = issue_refresh(session, user.id, row.family_id, now, settings)
session.commit()
return token_pair(settings, user, new_raw, now, cookie_mode, response)
@auth.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
def logout(
claims: Annotated[dict, Depends(get_current_claims)],
session: SessionDep,
settings: SettingsDep,
clock: ClockDep,
response: Response,
body: Annotated[Optional[RefreshIn], Body()] = None,
refresh_cookie: Annotated[Optional[str], Cookie(alias=REFRESH_COOKIE)] = None,
):
now = clock()
raw = body.refresh_token if body is not None else refresh_cookie
if raw:
row = session.scalar(select(RefreshToken).where(RefreshToken.token_hash == sha256_hex(raw)))
if row is not None and row.user_id == int(claims["sub"]):
revoke_family(session, row.family_id, now)
# Denylist the jti until exp + leeway: decode accepts the token until then, so a row purged
# at exp would resurrect it for the leeway window.
keep_until = claims_exp(claims) + timedelta(seconds=settings.leeway_seconds)
session.merge(RevokedAccessToken(jti=claims["jti"], expires_at=naive_utc(keep_until)))
session.commit()
response.delete_cookie(REFRESH_COOKIE, path="/auth")
response.status_code = status.HTTP_204_NO_CONTENT
return None
def claims_exp(claims: dict) -> datetime:
return datetime.fromtimestamp(claims["exp"], tz=timezone.utc)
def send_reset_email(outbox: Outbox, to: str, token: str) -> None:
outbox.send(to, "Reset your password", f"https://app.example.test/reset?token={token}")
def process_reset_request(engine: Engine, settings: Settings, now: datetime, outbox: Outbox, email: str) -> None:
"""Runs as a background task, AFTER the 202 has been sent. The lookup, the token row and the
e-mail happen here, so the request handler does identical work for known and unknown e-mails."""
with Session(engine) as session:
user = session.scalar(select(User).where(User.email == email))
if user is None or not user.is_active:
return
raw = new_opaque_token()
session.add(PasswordResetToken(
user_id=user.id, token_hash=sha256_hex(raw),
expires_at=naive_utc(now + timedelta(seconds=settings.reset_ttl_seconds)),
))
session.commit()
send_reset_email(outbox, user.email, raw)
@auth.post("/password-reset/request", status_code=status.HTTP_202_ACCEPTED)
def password_reset_request(
body: ResetRequestIn, background: BackgroundTasks, request: Request,
settings: SettingsDep, clock: ClockDep, outbox: OutboxDep,
):
# No branch on the account here: one add_task, one constant body, for every e-mail.
background.add_task(
process_reset_request, request.app.state.engine, settings, clock(), outbox,
body.email.strip().lower(),
)
return RESET_ACCEPTED
@auth.post("/password-reset/confirm", status_code=status.HTTP_204_NO_CONTENT)
def password_reset_confirm(body: ResetConfirmIn, session: SessionDep, clock: ClockDep):
now = naive_utc(clock())
row = session.scalar(
select(PasswordResetToken).where(PasswordResetToken.token_hash == sha256_hex(body.token))
)
if row is None or row.used_at is not None or row.expires_at <= now:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Invalid or expired reset token")
if not claim_once(session, PasswordResetToken, row.id, now): # single use, atomically
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Invalid or expired reset token")
user = session.get(User, row.user_id)
user.password_hash = hash_password(body.new_password)
user.failed_logins = 0
# Access tokens are stateless; bumping the version makes get_current_user refuse every token
# issued before this point, including ones issued earlier in the same second.
session.execute(
update(User).where(User.id == user.id).values(token_version=User.token_version + 1)
)
# Invalidate every other outstanding reset token and every refresh token of this user.
session.execute(
update(PasswordResetToken)
.where(PasswordResetToken.user_id == user.id, PasswordResetToken.used_at.is_(None))
.values(used_at=now)
)
session.execute(
update(RefreshToken)
.where(RefreshToken.user_id == user.id, RefreshToken.revoked_at.is_(None))
.values(revoked_at=now)
)
session.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
users = APIRouter(prefix="/users", tags=["users"])
@users.get("/me", response_model=UserOut)
def me(user: CurrentUser):
return UserOut(id=user.id, email=user.email, role=user.role)
# Every route of this router needs the admin role: the check cannot be forgotten per route.
admin = APIRouter(prefix="/admin", tags=["admin"], dependencies=[Depends(require_role("admin"))])
@admin.get("/stats")
def stats(session: SessionDep):
return {"users": len(session.scalars(select(User)).all())}
@admin.post("/api-keys", status_code=status.HTTP_201_CREATED)
def create_api_key(name: Annotated[str, Body(embed=True)], session: SessionDep):
prefix = "ak_" + new_opaque_token()[:8].replace("-", "x").replace("_", "x")
raw = prefix + "." + new_opaque_token()
session.add(ApiKey(name=name, prefix=prefix, key_hash=sha256_hex(raw)))
session.commit()
# Shown exactly once; only the hash is stored.
return {"api_key": raw, "prefix": prefix}
machine = APIRouter(prefix="/machine", tags=["machine"])
@machine.get("/ping")
def machine_ping(client: Annotated[ApiKey, Depends(get_api_client)]):
return {"client": client.name}
def create_app(settings: Optional[Settings] = None, engine: Optional[Engine] = None) -> FastAPI:
settings = settings or Settings()
engine = engine or make_engine(settings.database_url)
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(engine)
app.state.settings = settings
app.state.engine = engine
app.state.outbox = Outbox()
yield
engine.dispose()
app = FastAPI(title="Auth demo", lifespan=lifespan)
for r in (auth, users, admin, machine):
app.include_router(r)
return appAsymmetric keys with kid and rotation, for when other services must verify tokens without being able to mint them. verify applies exactly the HS256 path's checks (issuer, audience, leeway, require for iss aud sub iat nbf exp jti typ, and typ == "access"), because PyJWT's require defaults to an empty list ("Default: []. List of claims that must be present."):
"""Asymmetric signing with key rotation: the issuer signs with the newest private key and puts
its kid in the header; verifiers hold only public keys and pick one by kid."""
from typing import Dict, List
import jwt
from cryptography.hazmat.primitives.asymmetric import ed25519, rsa
class KeyRing:
def __init__(self) -> None:
self.private: Dict[str, object] = {}
self.order: List[str] = []
def add_ed25519(self, kid: str) -> None:
self.private[kid] = ed25519.Ed25519PrivateKey.generate()
self.order.append(kid)
def add_rsa(self, kid: str) -> None:
self.private[kid] = rsa.generate_private_key(public_exponent=65537, key_size=2048)
self.order.append(kid)
def retire(self, kid: str) -> None:
self.private.pop(kid)
self.order.remove(kid)
@property
def current_kid(self) -> str:
return self.order[-1]
def public_keys(self) -> Dict[str, object]:
"""What a JWKS endpoint would publish (as JWK JSON); here as key objects."""
return {kid: key.public_key() for kid, key in self.private.items()}
def alg_for(key: object) -> str:
return "EdDSA" if isinstance(key, ed25519.Ed25519PublicKey) else "RS256"
def sign(ring: KeyRing, claims: dict) -> str:
kid = ring.current_kid
key = ring.private[kid]
alg = "EdDSA" if isinstance(key, ed25519.Ed25519PrivateKey) else "RS256"
return jwt.encode(claims, key, algorithm=alg, headers={"kid": kid})
REQUIRED = ["iss", "aud", "sub", "iat", "nbf", "exp", "jti", "typ"]
def verify(public_keys: Dict[str, object], token: str, audience: str, issuer: str, leeway: int = 30) -> dict:
header = jwt.get_unverified_header(token) # only to choose the key; never to choose trust
key = public_keys.get(header.get("kid", ""))
if key is None:
raise jwt.InvalidTokenError("unknown kid")
# The algorithm comes from the KEY we hold, not from the header the attacker wrote.
# The same checks as the HS256 path in security.py: issuer, audience, leeway, required claims.
claims = jwt.decode(
token, key, algorithms=[alg_for(key)], audience=audience, issuer=issuer, leeway=leeway,
options={"require": REQUIRED},
)
if claims.get("typ") != "access":
raise jwt.InvalidTokenError("not an access token")
return claimsThe e-mail sender is a fake with an outbox, so tests can read the reset link:
"""A fake mailer: the real one would call SMTP or an e-mail API. Tests read the outbox."""
from dataclasses import dataclass, field
from typing import List, Tuple
@dataclass
class Outbox:
sent: List[Tuple[str, str, str]] = field(default_factory=list)
def send(self, to: str, subject: str, body: str) -> None:
self.sent.append((to, subject, body))The test fixtures: a fresh random secret key per run, a frozen clock installed through dependency_overrides, and two helpers:
import secrets
from datetime import datetime, timedelta, timezone
import pytest
from fastapi.testclient import TestClient
from app.deps import get_clock
from app.main import create_app
from app.settings import Settings
class FrozenClock:
"""Overrides get_clock: tests move time instead of sleeping."""
def __init__(self) -> None:
self.now = datetime.now(timezone.utc)
def __call__(self) -> datetime:
return self.now
def advance(self, **kw) -> None:
self.now += timedelta(**kw)
@pytest.fixture
def settings(tmp_path):
# A fresh random secret per test run: no real secret ever lives in the repo.
# A file database per test: every Session gets its own connection, as in production.
return Settings(
jwt_secret=secrets.token_urlsafe(48), cookie_secure=False, _env_file=None,
database_url=f"sqlite+pysqlite:///{tmp_path / 'auth.db'}",
)
@pytest.fixture
def clock():
return FrozenClock()
@pytest.fixture
def app(settings, clock):
app = create_app(settings)
app.dependency_overrides[get_clock] = lambda: clock
return app
@pytest.fixture
def client(app):
with TestClient(app) as c:
yield c
PASSWORD = "correct horse battery staple"
def signup(client, email="alice@example.test", password=PASSWORD):
r = client.post("/auth/signup", json={"email": email, "password": password})
assert r.status_code == 201, r.text
return r.json()
def login(client, email="alice@example.test", password=PASSWORD, **kw):
return client.post("/auth/token", data={"username": email, "password": password}, **kw)Login, hashing, enumeration, lockout, rehash and the OpenAPI scheme:
from sqlalchemy import select
from sqlalchemy.orm import Session
from app import security
from app.db import User
from app.security import password_hash
from pwdlib.hashers.bcrypt import BcryptHasher
from .conftest import PASSWORD, login, signup
def test_signup_stores_argon2id_hash_never_the_password(client, app):
signup(client)
with Session(app.state.engine) as s:
user = s.scalar(select(User))
assert user.password_hash.startswith("$argon2id$v=19$m=65536,t=3,p=4$")
assert PASSWORD not in user.password_hash
def test_same_password_gives_different_hashes_because_of_the_salt():
assert password_hash.hash(PASSWORD) != password_hash.hash(PASSWORD)
def test_login_returns_bearer_access_and_refresh(client):
signup(client)
r = login(client)
assert r.status_code == 200
body = r.json()
assert body["token_type"] == "bearer"
assert body["expires_in"] == 900
assert body["refresh_token"].startswith("rt_")
me = client.get("/users/me", headers={"Authorization": f"Bearer {body['access_token']}"})
assert me.status_code == 200 and me.json()["email"] == "alice@example.test"
def test_wrong_password_and_unknown_user_get_the_identical_response(client):
signup(client)
wrong = login(client, password="not the password at all")
unknown = login(client, email="nobody@example.test")
assert wrong.status_code == unknown.status_code == 401
assert wrong.json() == unknown.json() == {"detail": "Incorrect email or password"}
assert wrong.headers["www-authenticate"] == unknown.headers["www-authenticate"] == "Bearer"
def test_unknown_user_still_pays_for_one_argon2_verification(client, monkeypatch):
signup(client)
calls = []
real = security.password_hash.verify
monkeypatch.setattr(security.password_hash, "verify", lambda p, h: calls.append(h) or real(p, h))
login(client, email="nobody@example.test")
assert calls == [security.DUMMY_HASH]
def test_lockout_after_five_failures_keeps_the_generic_error(client):
signup(client)
for _ in range(5):
assert login(client, password="wrong password!!").status_code == 401
r = login(client) # the right password, but the account is locked
assert r.status_code == 401
assert r.json() == {"detail": "Incorrect email or password"}
def test_legacy_bcrypt_hash_verifies_and_is_upgraded_to_argon2id(client, app):
signup(client)
with Session(app.state.engine) as s:
user = s.scalar(select(User))
user.password_hash = BcryptHasher(rounds=10).hash(PASSWORD)
s.commit()
assert login(client).status_code == 200
with Session(app.state.engine) as s:
assert s.scalar(select(User)).password_hash.startswith("$argon2id$")
def test_overlong_login_password_is_rejected_before_hashing(client, monkeypatch):
signup(client)
calls = []
real = security.password_hash.verify_and_update
monkeypatch.setattr(security.password_hash, "verify_and_update",
lambda p, h: calls.append(len(p)) or real(p, h))
r = login(client, password="x" * 1_000_000)
assert r.status_code == 401 and r.json() == {"detail": "Incorrect email or password"}
assert calls == [] # argon2 never saw the megabyte
login(client, password="x" * 128)
assert calls == [128]
def test_login_is_form_data_not_json(client):
signup(client)
r = client.post("/auth/token", json={"username": "alice@example.test", "password": PASSWORD})
assert r.status_code == 422
def test_duplicate_signup_and_weak_password_rejected(client):
signup(client)
assert client.post("/auth/signup", json={"email": "alice@example.test", "password": PASSWORD}).status_code == 409
assert client.post("/auth/signup", json={"email": "b@example.test", "password": "fourteen chars"}).status_code == 422
def test_openapi_declares_the_password_flow_for_swagger_authorize(client):
schemes = client.get("/openapi.json").json()["components"]["securitySchemes"]
assert schemes["OAuth2PasswordBearer"] == {
"type": "oauth2",
"flows": {"password": {"scopes": {}, "tokenUrl": "auth/token"}},
}
assert schemes["APIKeyHeader"] == {"type": "apiKey", "in": "header", "name": "X-API-Key"}Access-token negatives: no header, expired, leeway, wrong aud/iss, missing claims, tampered payload, alg: none, a foreign key, a refresh token used as an access token, a non-integer sub (401, not 500), EdDSA rotation, the asymmetric verifier applying the same checks as HS256, and the RS256-to-HS256 confusion:
import base64
import json
from datetime import timedelta
import jwt
import pytest
from app.keys import KeyRing, sign, verify
from app.security import create_access_token, decode_access_token, utcnow
from .conftest import login, signup
def bearer(token):
return {"Authorization": f"Bearer {token}"}
def test_missing_header_is_401_with_www_authenticate(client):
r = client.get("/users/me")
assert r.status_code == 401
assert r.json() == {"detail": "Not authenticated"}
assert r.headers["www-authenticate"] == "Bearer"
def test_expired_token_is_rejected(client, settings):
signup(client)
old = create_access_token(settings, subject="1", role="user", now=utcnow() - timedelta(hours=1))
r = client.get("/users/me", headers=bearer(old))
assert r.status_code == 401
assert r.json() == {"detail": "Token expired"}
assert r.headers["www-authenticate"] == "Bearer"
def test_leeway_accepts_a_token_that_expired_seconds_ago(settings):
# exp = now - 10 s; leeway is 30 s, so clock skew between servers does not break it.
t = create_access_token(settings, subject="1", role="user",
now=utcnow() - timedelta(seconds=settings.access_ttl_seconds + 10))
assert decode_access_token(settings, t)["sub"] == "1"
with pytest.raises(jwt.ExpiredSignatureError):
decode_access_token(settings.model_copy(update={"leeway_seconds": 0}), t)
def test_wrong_audience_and_wrong_issuer_are_rejected(settings):
t = create_access_token(settings.model_copy(update={"jwt_audience": "billing-api"}), subject="1", role="user")
with pytest.raises(jwt.InvalidAudienceError):
decode_access_token(settings, t)
t = create_access_token(settings.model_copy(update={"jwt_issuer": "https://evil.test"}), subject="1", role="user")
with pytest.raises(jwt.InvalidIssuerError):
decode_access_token(settings, t)
def test_missing_required_claim_is_rejected(settings):
t = jwt.encode({"sub": "1", "exp": utcnow() + timedelta(minutes=5)},
settings.jwt_secret.get_secret_value(), algorithm="HS256")
with pytest.raises(jwt.MissingRequiredClaimError):
decode_access_token(settings, t)
def test_tampered_payload_fails_the_signature(client, settings):
signup(client)
token = login(client).json()["access_token"]
h, p, s = token.split(".")
claims = json.loads(base64.urlsafe_b64decode(p + "=="))
claims["role"] = "admin"
forged_p = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()
r = client.get("/users/me", headers=bearer(f"{h}.{forged_p}.{s}"))
assert r.status_code == 401 and r.json() == {"detail": "Could not validate credentials"}
def test_alg_none_token_is_rejected(client, settings):
signup(client)
unsigned = jwt.encode({"sub": "1", "iss": settings.jwt_issuer, "aud": settings.jwt_audience,
"exp": utcnow() + timedelta(minutes=5)}, None, algorithm="none")
assert client.get("/users/me", headers=bearer(unsigned)).status_code == 401
def test_token_signed_with_another_secret_is_rejected(client, settings):
signup(client)
other = settings.model_copy(update={"jwt_secret": settings.jwt_secret.__class__("x" * 48)})
t = create_access_token(other, subject="1", role="user")
assert client.get("/users/me", headers=bearer(t)).status_code == 401
def test_refresh_token_is_not_an_access_token(client):
signup(client)
rt = login(client).json()["refresh_token"]
assert client.get("/users/me", headers=bearer(rt)).status_code == 401
ISS = "https://auth.example.test"
def full_claims(**override):
now = utcnow()
claims = {"iss": ISS, "aud": "notes-api", "sub": "1", "iat": now, "nbf": now,
"exp": now + timedelta(minutes=15), "jti": "j1", "typ": "access"}
claims.update(override)
return {k: v for k, v in claims.items() if v is not None}
def test_eddsa_with_kid_and_rotation():
ring = KeyRing()
ring.add_ed25519("2026-10")
old = sign(ring, full_claims())
ring.add_ed25519("2026-11") # rotate: new tokens use the new kid
new = sign(ring, full_claims())
assert jwt.get_unverified_header(new) == {"alg": "EdDSA", "kid": "2026-11", "typ": "JWT"}
pub = ring.public_keys()
assert verify(pub, old, "notes-api", ISS)["sub"] == "1" # old key still published: old tokens live
ring.retire("2026-10")
with pytest.raises(jwt.InvalidTokenError, match="unknown kid"):
verify(ring.public_keys(), old, "notes-api", ISS)
assert verify(ring.public_keys(), new, "notes-api", ISS)["sub"] == "1"
@pytest.mark.parametrize("override, error", [
({"exp": None}, jwt.MissingRequiredClaimError),
({"iat": None}, jwt.MissingRequiredClaimError),
({"iss": "https://evil.test"}, jwt.InvalidIssuerError),
({"aud": "billing-api"}, jwt.InvalidAudienceError),
({"typ": "refresh"}, jwt.InvalidTokenError),
({"exp": utcnow() - timedelta(minutes=5)}, jwt.ExpiredSignatureError),
])
def test_asymmetric_verifier_applies_the_same_checks_as_hs256(override, error):
ring = KeyRing()
ring.add_ed25519("k1")
with pytest.raises(error):
verify(ring.public_keys(), sign(ring, full_claims(**override)), "notes-api", ISS)
def test_non_integer_sub_is_401_not_500(client, settings):
signup(client)
t = create_access_token(settings, subject="not-an-integer", role="user")
r = client.get("/users/me", headers=bearer(t))
assert r.status_code == 401 and r.json() == {"detail": "Could not validate credentials"}
def test_rs256_public_key_cannot_be_used_as_an_hs256_secret():
ring = KeyRing()
ring.add_rsa("rsa-1")
pub = ring.public_keys()["rsa-1"]
from cryptography.hazmat.primitives import serialization
pem = pub.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
# The classic algorithm-confusion attack: sign HS256 with the public key as the HMAC secret.
with pytest.raises(jwt.InvalidKeyError):
jwt.encode({"sub": "1"}, pem, algorithm="HS256")
# And verification pins RS256 from the key type, so a forged HS256 header is refused anyway.
forged_header = base64.urlsafe_b64encode(b'{"alg":"HS256","kid":"rsa-1","typ":"JWT"}').rstrip(b"=").decode()
body = base64.urlsafe_b64encode(b'{"sub":"1","aud":"notes-api"}').rstrip(b"=").decode()
with pytest.raises(jwt.InvalidAlgorithmError):
verify(ring.public_keys(), f"{forged_header}.{body}.AAAA", "notes-api", ISS)Refresh rotation, reuse detection, the two concurrency tests (a rollback in another session, and two threads racing for one write lock), logout with a denylist purge inside the leeway, and cookie mode with CSRF:
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.db import RefreshToken
from .conftest import login, signup
def tokens(client):
signup(client)
return login(client).json()
def test_refresh_rotates_and_the_old_token_dies(client):
t1 = tokens(client)
r = client.post("/auth/refresh", json={"refresh_token": t1["refresh_token"]})
assert r.status_code == 200
t2 = r.json()
assert t2["refresh_token"] != t1["refresh_token"]
assert client.get("/users/me", headers={"Authorization": f"Bearer {t2['access_token']}"}).status_code == 200
def test_reused_refresh_token_revokes_the_whole_family(client):
t1 = tokens(client)
t2 = client.post("/auth/refresh", json={"refresh_token": t1["refresh_token"]}).json()
# An attacker (or a buggy client) replays the already-rotated token...
r = client.post("/auth/refresh", json={"refresh_token": t1["refresh_token"]})
assert r.status_code == 401
assert r.json() == {"detail": "Refresh token reuse detected"}
# ...and the legitimate newest token is dead too: the family was revoked.
r = client.post("/auth/refresh", json={"refresh_token": t2["refresh_token"]})
assert r.status_code == 401 and r.json() == {"detail": "Refresh token reuse detected"}
def test_reuse_does_not_touch_other_sessions(client):
signup(client)
phone = login(client).json()
laptop = login(client).json()
client.post("/auth/refresh", json={"refresh_token": phone["refresh_token"]})
client.post("/auth/refresh", json={"refresh_token": phone["refresh_token"]}) # reuse on phone
assert client.post("/auth/refresh", json={"refresh_token": laptop["refresh_token"]}).status_code == 200
def test_expired_refresh_token(client, clock, settings):
t1 = tokens(client)
clock.advance(seconds=settings.refresh_ttl_seconds + 1)
r = client.post("/auth/refresh", json={"refresh_token": t1["refresh_token"]})
assert r.status_code == 401 and r.json() == {"detail": "Refresh token expired"}
def test_unknown_refresh_token(client):
tokens(client)
r = client.post("/auth/refresh", json={"refresh_token": "rt_made-up"})
assert r.status_code == 401 and r.json() == {"detail": "Could not validate credentials"}
def test_only_the_hash_is_stored(client, app):
t1 = tokens(client)
with Session(app.state.engine) as s:
rows = s.scalars(select(RefreshToken)).all()
assert len(rows) == 1
assert rows[0].token_hash != t1["refresh_token"] and len(rows[0].token_hash) == 64
def test_logout_revokes_refresh_family_and_denylists_the_access_jti(client):
t1 = tokens(client)
auth = {"Authorization": f"Bearer {t1['access_token']}"}
r = client.post("/auth/logout", json={"refresh_token": t1["refresh_token"]}, headers=auth)
assert r.status_code == 204
assert client.get("/users/me", headers=auth).status_code == 401
assert client.post("/auth/refresh", json={"refresh_token": t1["refresh_token"]}).status_code == 401
def test_cookie_mode_sets_httponly_secure_samesite_and_needs_csrf(client):
signup(client)
r = login(client, headers={"X-Client": "browser"})
assert "refresh_token" not in r.json()
set_cookie = r.headers.get_list("set-cookie")
rt = next(c for c in set_cookie if c.startswith("refresh_token="))
assert "HttpOnly" in rt and "SameSite=strict" in rt and "Path=/auth" in rt
csrf = client.cookies.get("csrf_token")
# Cookies go automatically, so a forged cross-site POST would carry them; without the header it fails.
assert client.post("/auth/refresh").status_code == 403
assert client.post("/auth/refresh", headers={"X-CSRF-Token": "guess"}).status_code == 403
ok = client.post("/auth/refresh", headers={"X-CSRF-Token": csrf})
assert ok.status_code == 200 and "access_token" in ok.json()
def test_cookie_secure_flag_on_by_default(settings, clock):
from fastapi.testclient import TestClient
from app.deps import get_clock
from app.main import create_app
app = create_app(settings.model_copy(update={"cookie_secure": True}))
app.dependency_overrides[get_clock] = lambda: clock
with TestClient(app, base_url="https://testserver") as c:
signup(c)
r = login(c, headers={"X-Client": "browser"})
assert all("Secure" in h for h in r.headers.get_list("set-cookie"))
def _row_id(app, raw):
from app.security import sha256_hex
with Session(app.state.engine) as s:
return s.scalar(select(RefreshToken.id).where(RefreshToken.token_hash == sha256_hex(raw)))
def test_a_rollback_elsewhere_cannot_undo_a_claim(client, app, clock):
"""Two sessions = two connections. B's rollback must not touch A's claim (it did with StaticPool)."""
from app.main import claim_once
rid = _row_id(app, tokens(client)["refresh_token"])
with Session(app.state.engine) as a, Session(app.state.engine) as b:
assert b.get(RefreshToken, rid).used_at is None # B read "unused"
b.rollback()
assert claim_once(a, RefreshToken, rid, clock()) is True
a.commit()
assert claim_once(b, RefreshToken, rid, clock()) is False
b.commit()
with Session(app.state.engine) as s:
assert s.get(RefreshToken, rid).used_at is not None
def test_two_concurrent_claims_only_one_wins(client, app, clock):
"""A claims inside an open transaction; B (another thread, another connection) blocks on the
write lock, and once A commits B's UPDATE matches zero rows."""
import threading
from app.main import claim_once
rid = _row_id(app, tokens(client)["refresh_token"])
results = {}
a = Session(app.state.engine)
results["a"] = claim_once(a, RefreshToken, rid, clock()) # A holds the write lock, uncommitted
def other():
with Session(app.state.engine) as b:
results["b"] = claim_once(b, RefreshToken, rid, clock())
b.commit()
t = threading.Thread(target=other)
t.start()
t.join(0.3)
assert t.is_alive() # B is waiting for A
a.commit()
a.close()
t.join(5)
assert results == {"a": True, "b": False}
def test_logged_out_token_stays_denied_through_the_leeway_after_a_purge(client, app, settings):
from datetime import timedelta
from app.db import purge_denylist
from app.deps import naive_utc
from app.security import create_access_token, utcnow
signup(client)
# exp was 10 s ago: still accepted because of the 30 s leeway.
t = create_access_token(settings, subject="1", role="user",
now=utcnow() - timedelta(seconds=settings.access_ttl_seconds + 10))
auth = {"Authorization": f"Bearer {t}"}
assert client.get("/users/me", headers=auth).status_code == 200
assert client.post("/auth/logout", headers=auth).status_code == 204
with Session(app.state.engine) as s:
assert purge_denylist(s, naive_utc(utcnow())) == 0 # exp passed, exp + leeway did not
s.commit()
assert client.get("/users/me", headers=auth).status_code == 401
with Session(app.state.engine) as s: # after exp + leeway the row may go
assert purge_denylist(s, naive_utc(utcnow() + timedelta(seconds=settings.leeway_seconds))) == 1
s.commit()
def test_planted_csrf_cookie_does_not_pass(client):
signup(client)
login(client, headers={"X-Client": "browser"})
# An attacker who can write cookies (sibling subdomain) plants a matching cookie/header pair.
client.cookies.set("csrf_token", "attacker.0000")
assert client.post("/auth/refresh", headers={"X-CSRF-Token": "attacker.0000"}).status_code == 403Password reset:
from .conftest import PASSWORD, login, signup
NEW = "a brand new long passphrase"
def request_reset(client, email="alice@example.test"):
return client.post("/auth/password-reset/request", json={"email": email})
def token_from_outbox(app):
to, subject, body = app.state.outbox.sent[-1]
return body.split("token=")[1]
def test_known_and_unknown_email_get_the_same_answer(client, app):
signup(client)
a = request_reset(client)
b = request_reset(client, "nobody@example.test")
assert a.status_code == b.status_code == 202
assert a.content == b.content
assert dict(a.headers) == dict(b.headers)
assert len(app.state.outbox.sent) == 1 # only the real user got mail (via BackgroundTasks)
def test_handler_does_the_same_work_for_both_and_defers_the_lookup(client, monkeypatch):
"""The handler only schedules process_reset_request; the user lookup runs after the response."""
from app import main
scheduled = []
monkeypatch.setattr(main, "process_reset_request", lambda *a: scheduled.append(a[-1]))
signup(client)
request_reset(client)
request_reset(client, "nobody@example.test")
assert scheduled == ["alice@example.test", "nobody@example.test"]
def test_reset_token_is_single_use(client, app):
signup(client)
request_reset(client)
tok = token_from_outbox(app)
assert client.post("/auth/password-reset/confirm", json={"token": tok, "new_password": NEW}).status_code == 204
again = client.post("/auth/password-reset/confirm", json={"token": tok, "new_password": "yet another passphrase"})
assert again.status_code == 400 and again.json() == {"detail": "Invalid or expired reset token"}
assert login(client, password=NEW).status_code == 200
assert login(client, password=PASSWORD).status_code == 401
def test_reset_token_expires(client, app, clock, settings):
signup(client)
request_reset(client)
tok = token_from_outbox(app)
clock.advance(seconds=settings.reset_ttl_seconds + 1)
assert client.post("/auth/password-reset/confirm", json={"token": tok, "new_password": NEW}).status_code == 400
def test_reset_kills_existing_sessions_and_older_reset_links(client, app):
signup(client)
t = login(client).json()
request_reset(client)
first = token_from_outbox(app)
request_reset(client)
second = token_from_outbox(app)
assert client.post("/auth/password-reset/confirm", json={"token": second, "new_password": NEW}).status_code == 204
assert client.post("/auth/refresh", json={"refresh_token": t["refresh_token"]}).status_code == 401
assert client.post("/auth/password-reset/confirm", json={"token": first, "new_password": NEW}).status_code == 400
def test_reset_unlocks_a_locked_account(client, app):
signup(client)
for _ in range(5):
login(client, password="wrong password!!")
request_reset(client)
client.post("/auth/password-reset/confirm", json={"token": token_from_outbox(app), "new_password": NEW})
assert login(client, password=NEW).status_code == 200
def test_reset_cuts_off_access_tokens_issued_in_the_same_second(client, app, clock):
signup(client)
old = login(client).json()["access_token"]
# No clock.advance: login and reset happen at the same instant. A second-truncated iat
# comparison would keep `old` alive; the token_version counter does not.
request_reset(client)
client.post("/auth/password-reset/confirm", json={"token": token_from_outbox(app), "new_password": NEW})
assert client.get("/users/me", headers={"Authorization": f"Bearer {old}"}).status_code == 401
fresh = login(client, password=NEW).json()["access_token"]
assert client.get("/users/me", headers={"Authorization": f"Bearer {fresh}"}).status_code == 200
def test_reset_token_stored_only_as_hash(client, app):
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.db import PasswordResetToken
signup(client)
request_reset(client)
tok = token_from_outbox(app)
with Session(app.state.engine) as s:
assert s.scalar(select(PasswordResetToken)).token_hash != tok401 vs 403, API keys, and an override that skips auth:
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.db import ApiKey, User
from .conftest import login, signup
def make_admin(client, app):
signup(client, "root@example.test")
with Session(app.state.engine) as s:
s.scalar(select(User).where(User.email == "root@example.test")).role = "admin"
s.commit()
return {"Authorization": f"Bearer {login(client, 'root@example.test').json()['access_token']}"}
def test_401_without_identity_403_with_the_wrong_role(client, app):
assert client.get("/admin/stats").status_code == 401
signup(client)
user = {"Authorization": f"Bearer {login(client).json()['access_token']}"}
r = client.get("/admin/stats", headers=user)
assert r.status_code == 403 and "www-authenticate" not in r.headers
assert client.get("/admin/stats", headers=make_admin(client, app)).json() == {"users": 2}
def test_api_key_flow_hash_stored_and_revocation(client, app):
admin = make_admin(client, app)
created = client.post("/admin/api-keys", json={"name": "billing-cron"}, headers=admin).json()
key = created["api_key"]
assert client.get("/machine/ping", headers={"X-API-Key": key}).json() == {"client": "billing-cron"}
with Session(app.state.engine) as s:
row = s.scalar(select(ApiKey))
assert key not in (row.key_hash, row.prefix) and key.startswith(row.prefix + ".")
from datetime import datetime
row.revoked_at = datetime(2026, 11, 29)
s.commit()
assert client.get("/machine/ping", headers={"X-API-Key": key}).status_code == 401
def test_bad_or_missing_api_key(client, app):
admin = make_admin(client, app)
key = client.post("/admin/api-keys", json={"name": "c"}, headers=admin).json()["api_key"]
for headers in ({}, {"X-API-Key": "nonsense"}, {"X-API-Key": key[:-1] + "A" if key[-1] != "A" else key[:-1] + "B"}):
r = client.get("/machine/ping", headers=headers)
assert r.status_code == 401 and r.json() == {"detail": "Invalid API key"}
assert r.headers["www-authenticate"] == "APIKey"
def test_dependency_override_skips_auth_in_unit_tests(app):
from fastapi.testclient import TestClient
from app.deps import get_current_user
app.dependency_overrides[get_current_user] = lambda: User(id=7, email="t@example.test", role="user")
with TestClient(app) as c:
assert c.get("/users/me").json() == {"id": 7, "email": "t@example.test", "role": "user"}The whole flow over httpx AsyncClient:
"""The whole flow over httpx.AsyncClient + ASGITransport (no server, no network)."""
import httpx
import pytest
from .conftest import PASSWORD
@pytest.mark.anyio
async def test_signup_login_me_refresh_logout(app):
# ASGITransport does not run the lifespan; enter it through the router's lifespan context.
async with app.router.lifespan_context(app):
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as ac:
r = await ac.post("/auth/signup", json={"email": "a@example.test", "password": PASSWORD})
assert r.status_code == 201
r = await ac.post("/auth/token", data={"username": "a@example.test", "password": PASSWORD})
pair = r.json()
auth = {"Authorization": f"Bearer {pair['access_token']}"}
assert (await ac.get("/users/me", headers=auth)).json()["email"] == "a@example.test"
r = await ac.post("/auth/refresh", json={"refresh_token": pair["refresh_token"]})
new = r.json()
auth = {"Authorization": f"Bearer {new['access_token']}"}
r = await ac.post("/auth/logout", json={"refresh_token": new["refresh_token"]}, headers=auth)
assert r.status_code == 204
assert (await ac.get("/users/me", headers=auth)).status_code == 401
@pytest.fixture
def anyio_backend():
return "asyncio"All 65 tests pass in about 4 s (real run, below in the Lab). Most of that time is argon2id. The project's pyproject.toml pins every version above, and requirements.lock is the resolved set from a fresh install.
The Python angle
Three Python details carry most of the weight. secrets (since 3.6) is the only standard-library source of randomness meant for secrets; its docs say "As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case expected for the secrets module". secrets.compare_digest and hmac.compare_digest are the constant-time comparison, and SecretStr.__eq__ uses it too. And Pydantic's SecretStr stops the secret key from ending up in a traceback or a log line, but not everywhere: on the build machine, a too-short secret makes pydantic's ValidationError print input_value='CHANGE-ME' (real run), so never log validation errors of the settings object in production.
The concept catalogue
Each block has the same shape: plain words, the common misunderstanding, the definition with its source, a table or a timeline, and the fix.
OAuth2PasswordBearer, tokenUrl and the Swagger Authorize button Must-know
In plain words: OAuth2PasswordBearer is a dependency that pulls the token out of the Authorization: Bearer … header and hands you the string. Its tokenUrl tells the OpenAPI schema, and so Swagger UI's "Authorize" button, where to post the username and password.
Common misunderstanding: "It validates the JWT" or "it creates the /token route". It does neither. It does not know what a JWT is, and tokenUrl is only a pointer in the schema; you write the route.
Definition: The FastAPI tutorial: "If it doesn't see an Authorization header, or the value doesn't have a Bearer token, it will respond with a 401 status code error (UNAUTHORIZED) directly." After adding it, "You already have a shiny new 'Authorize' button." The schema it adds is real output from the snippet:
1 oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
2 -> /openapi.json components.securitySchemes:
3 {"OAuth2PasswordBearer": {"type": "oauth2",
4 "flows": {"password": {"scopes": {}, "tokenUrl": "auth/token"}}}}
5 Swagger "Authorize" -> POST auth/token (form: username, password) -> stores access_token
6 every "Try it out" -> Authorization: Bearer <access_token>| Input | OAuth2PasswordBearer returns | Response |
|---|---|---|
Authorization: Bearer abc | "abc" | your code decides |
| No header | (raises) | 401, WWW-Authenticate: Bearer, Not authenticated |
Authorization: Basic … | (raises) | 401 |
auto_error=False and no header | None | your code decides (optional auth) |
Fix / how to use it: keep tokenUrl relative ("auth/token", as in the docs) so it still works behind a path prefix; use auto_error=False only for routes where anonymous access is allowed; put the actual check in get_current_user.
OAuth2PasswordRequestForm: the login form Must-know
In plain words: the login endpoint receives form fields username and password (plus optional scope, client_id, client_secret, grant_type) because that is the OAuth2 password flow's wire format, and Swagger's Authorize dialog sends exactly that.
Common misunderstanding: "Using it makes my API an OAuth2-compliant server." It is only the wire format of a grant that RFC 9700 says must not be used. And "I can post JSON to it": A JSON body gets a 422 (test_login_is_form_data_not_json). It also needs python-multipart installed, as every form does.
Definition: The tutorial: "OAuth2 specifies that when using the 'password flow' (that we are using) the client/user must send username and password fields as form data." The field is called username even when you log in by e-mail.
RFC 9700 §2.4 is unconditional: "The resource owner password credentials grant [RFC6749] MUST NOT be used. This grant type insecurely exposes the credentials of the resource owner to the client. Even if the client is benign, usage of this grant results in an increased attack surface (i.e., credentials can leak in more places than just the authorization server) and in training users to enter their credentials in places other than the authorization server." It also notes the grant "is not designed to work with two-factor authentication". There is no first-party exception. This chapter still teaches OAuth2PasswordRequestForm because it is how the FastAPI docs build a login endpoint and how Swagger's "Authorize" button talks to it; read it as "a login form whose field names follow OAuth2", not as running an OAuth2 authorization server. Here the API that checks the password is the same service that stores it, so the credentials do not travel further than the server that owns them. Once a separate client, a second app, MFA or SSO is involved, the compliant alternatives are: the authorization code grant with PKCE ("Public clients MUST use PKCE", §2.1.1) against an identity provider; plain first-party session cookies for a server-rendered site; and client credentials or API keys for machines. They are in OAuth 2.0, OIDC & SSO.
| Field | Required | In the snippet |
|---|---|---|
username | yes | the e-mail, lower-cased |
password | yes | verified with argon2id |
scope | no | space-separated; see scopes preview |
grant_type | no (OAuth2PasswordRequestFormStrict: must be password) | not checked |
client_id / client_secret | no | not used |
Fix / how to use it: form: Annotated[OAuth2PasswordRequestForm, Depends()]; normalise the username the same way as at signup; never log the form.
Status codes: 401 vs 403 and WWW-Authenticate Must-know
In plain words: 401 means "I don't know who you are (or your proof is bad), try again with credentials". 403 means "I know who you are, and the answer is no". A 401 must say how to authenticate, in WWW-Authenticate.
Common misunderstanding: "403 for a bad token." A bad, expired or revoked token is a 401 so the client knows to refresh or log in. And until FastAPI 0.122.0 some security classes (HTTPBearer, APIKeyHeader…) answered missing credentials with 403; since then they return 401.
Definition: RFC 6750 §3.1: invalid_token: "The access token provided is expired, revoked, malformed, or invalid for other reasons. The resource SHOULD respond with the HTTP 401 (Unauthorized) status code." insufficient_scope: "The resource server SHOULD respond with the HTTP 403 (Forbidden) status code". The FastAPI security reference repeats RFC 9110: an error of 401 "must" also return a WWW-Authenticate header. The 0.122.0 release note: "Use 401 status code in security classes when credentials are missing."
| Case | Status | WWW-Authenticate | Test |
|---|---|---|---|
| No credentials | 401 | Bearer | test_missing_header_is_401_with_www_authenticate |
| Invalid / expired / revoked token | 401 | Bearer | test_expired_token_is_rejected |
| Valid token, wrong role | 403 | none | test_401_without_identity_403_with_the_wrong_role |
| Bad API key | 401 | APIKey | test_bad_or_missing_api_key |
| Login failure | 401 (FastAPI docs); RFC 6749 §5.2 says 400 invalid_grant | Bearer | test_wrong_password_and_unknown_user_get_the_identical_response |
Fix / how to use it: one credentials_error() helper for every 401 so the header is never forgotten; 403 only after authentication succeeded; if you follow RFC 6749 strictly at the token endpoint, return 400 with {"error": "invalid_grant"}, but do it for every failure alike.
Password hashing: argon2id, bcrypt, salt and work factor Must-know
In plain words: you never store the password, only a slow fingerprint of it. "Slow" is the point: one login can afford 25 ms, an attacker trying a billion guesses cannot. A random salt makes the same password hash differently for every user, so one cracked hash or one precomputed table does not unlock everyone.
Common misunderstanding: "SHA-256 with a salt is fine." SHA-256 is designed to be fast; the before app's hash takes microseconds (real timing: 0.39 ms per whole login request, versus 24.6 ms with argon2id). Another one: "encrypt the passwords". Encryption can be reversed by whoever has the key.
Definition: OWASP Password Storage Cheat Sheet: "Use Argon2id with a minimum configuration of 19 MiB of memory, an iteration count of 2, and 1 degree of parallelism." "For legacy systems using bcrypt, use a work factor of 10 or more and with a password limit of 72 bytes." On the work factor: "As a general rule, calculating a hash should take less than one second." argon2-cffi's defaults are time_cost=3, memory_cost=65536, parallelism=4, hash_len=32, salt_len=16 (since 21.2.0, the RFC 9106 low-memory profile), well above the OWASP minimum.
$argon2id$v=19$m=65536,t=3,p=4$<salt, base64>$<hash, base64>
| | | | |
1 alg 2 v 3 memory 4 passes 5 lanes -> all parameters travel with the hash,
(KiB) so changing them later is safe
$2b$12$<22-char salt><31-char hash> -> bcrypt: prefix, cost (2^12 rounds), salt+hash| Algorithm | Parameters (here) | Strength | Limit / caveat |
|---|---|---|---|
| argon2id | m=64 MiB, t=3, p=4 | Memory-hard, resists GPUs | Memory per login: size workers accordingly |
| bcrypt | cost 12 (pwdlib BcryptHasher(rounds: int = 12)) | Good, 25+ years old | 72-byte input limit: bcrypt 4.3.0 silently ignores the rest (real run); bcrypt 5.0 raises |
| scrypt | N=2^17, r=8, p=1 (OWASP) | Memory-hard | Less library support in FastAPI land |
| PBKDF2-HMAC-SHA256 | 600,000 iterations (OWASP) | FIPS-approved | Not memory-hard |
| SHA-256, MD5 | none | Unfit | Billions of guesses per second |
Fix / how to use it: argon2id with the library defaults, measured on your hardware (one hash took 23.0 ms on the build machine); a maximum password length (128 here, enforced at signup, reset and login: OAuth2PasswordRequestForm has no limit of its own, so the login route rejects longer input with the generic 401 before hashing, test_overlong_login_password_is_rejected_before_hashing) so a megabyte "password" cannot burn CPU; never truncate silently.
pwdlib, passlib deprecated, and verify and rehash Must-know
In plain words: pwdlib is a small wrapper that hashes with the first algorithm in its list and can verify with any of them. When an old hash (bcrypt, or argon2 with weaker parameters) verifies, it hands you a fresh hash to store: users migrate one login at a time.
Common misunderstanding: "passlib is the standard, use CryptContext." The original passlib's last release, 1.7.4, is from October 2020; the pwdlib README says that "Starting Python 3.13, passlib won't work anymore", because it imports the crypt module that PEP 594 removed. Treat it as passlib deprecated for new code. The nuance: the libpass fork continued it (1.7.5 to 1.9.4 on PyPI as libpass), and on 2026-11-23 it started publishing as passlib 1.9.5 again, requiring Python 3.11+. The FastAPI docs still recommend pwdlib and mention passlib only "for working with outdated hashes" (pwdlib "does not include legacy algorithms").
Definition: pwdlib's verify_and_update (0.2.1 source): it "Verifies if a password matches a given hash and updates the hash if necessary", returning "a tuple containing a boolean indicating if the password matches the hash, and an updated hash if the current hasher or the hash itself needs to be updated". The FastAPI docs switched from passlib to pwdlib with argon2 in 0.118.0 (PR #13917, which cites the crypt removal).
Verify and rehash in the snippet (test_legacy_bcrypt_hash_verifies_and_is_upgraded_to_argon2id)
1 stored: $2b$10$... (bcrypt, from a Laravel import)
2 verify_and_update(pw, stored) -> BcryptHasher.identify -> verify ok
3 hasher != current_hasher (Argon2Hasher) -> new_hash = argon2id(pw)
4 user.password_hash = new_hash; commit -> next login takes the argon2id path| Tool | Status (2026-11) | Python | Use for |
|---|---|---|---|
pwdlib 0.4.2 | Active, recommended by FastAPI | 3.11+ (0.2.1 for 3.8/3.9) | New code |
argon2-cffi directly | Active | 3.8+ | When you need only argon2 |
bcrypt directly | Active (pyca) | 3.8+ | Only bcrypt; mind 72 bytes |
passlib 1.7.4 (original) | Unmaintained since 2020 | breaks on 3.13 | Nothing new |
passlib 1.9.5 / libpass (fork) | Active again | 3.11+ | Migrating dozens of legacy schemes |
Fix / how to use it: PasswordHash((Argon2Hasher(), BcryptHasher())), always call verify_and_update, store the new hash when it is not None.
Choosing a JWT library: PyJWT vs python-jose Important
In plain words: both sign and verify JWTs. PyJWT is maintained, small and what the FastAPI docs use since 2024. python-jose went years without a release and had two security advisories in 2024.
Common misunderstanding: "python-jose is fine, the tutorial used it." It did, from 0.59.0 (2020) until 0.111.1 (July 2024, PR #11589: "Update JWT auth documentation to use PyJWT instead of python-jose").
Definition: GitHub advisories: CVE-2024-33663, "python-jose algorithm confusion with OpenSSH ECDSA keys", affected < 3.4.0, patched 3.4.0; CVE-2024-33664, "python-jose denial of service via compressed JWE content", affected < 3.4.0, patched 3.4.0. PyPI: python-jose 3.3.0 was released 2021-06-05 and 3.4.0 only 2025-02-18. PyJWT has its own history: CVE-2022-29217, "Key confusion through non-blocklisted public key formats", affected >= 1.5.0, < 2.4.0; 2.10.0 added validation of sub and jti; 2.10.1 fixed "partial matching of iss claim" (GHSA-75c5-xw7c-p5pm); 2.11.0 added InsecureKeyLengthWarning.
| Library | Latest (2026-11) | JWE | Notes |
|---|---|---|---|
| PyJWT 2.15.1 | 2026-09-28 | No | jwt.decode(..., algorithms=[...]) required; [crypto] extra for RS/ES/EdDSA |
| python-jose 3.5.0 | 2025-05-28 | Yes | CVEs fixed in 3.4.0; slower cadence |
| joserfc / authlib | active | Yes | When you need JWE or the full JOSE suite |
Fix / how to use it: PyJWT ≥ 2.10.1 (the snippet pins 2.15.1); install PyJWT[crypto] if you use RS256 or EdDSA; always pass algorithms=.
Access tokens and claims: sub, exp, iat, nbf, jti, aud, iss, leeway Must-know
In plain words: the access token is a signed note that says who (sub), issued by whom (iss), for whom (aud), when (iat), valid from (nbf) and until (exp), with a unique id (jti). The server checks every one of those, with a small leeway because server clocks drift.
Common misunderstanding: "jwt.decode checks everything by default." PyJWT checks exp, nbf and iat only if they are present. A token with an aud fails (Invalid audience) unless you pass audience=, but iss is not checked at all without issuer=: a token with "iss": "evil" decodes fine. A claim is only required if you list it in options={"require": [...]}; a token without exp passes a decode that did not require it (all four are real runs, runs/probe-pyjwt-defaults.txt).
Definition: RFC 7519 §4.1.4: "The 'exp' (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing", and "Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew." sub must be a string (StringOrURI); PyJWT validates that since 2.10.0, so str(user.id).
Decoded access token from the lab (real; signature omitted)
1 header : {"alg": "HS256", "typ": "JWT"}
2 claims : aud exp iat iss jti nbf role sub typ exp - iat = 900
3 decode : algorithms=["HS256"] audience="notes-api" issuer="https://auth.example.test"
4 leeway=30 require=[exp iat nbf sub jti iss aud]
5 then : typ == "access"? jti in denylist? int(sub)? user active? ver == users.token_version?| Claim | Meaning | Checked by | Failure (PyJWT exception) |
|---|---|---|---|
iss | Issuer | issuer= | InvalidIssuerError |
aud | Audience | audience= | InvalidAudienceError |
sub | Subject (user id, string) | your lookup | InvalidSubjectError if not a string |
exp | Expiry | always if present, require | ExpiredSignatureError |
nbf | Not before | always if present | ImmatureSignatureError |
iat | Issued at | type check | InvalidIssuedAtError |
ver (custom) | users.token_version at issue time | get_current_user; a reset increments the column | 401 |
jti | Token id | denylist lookup | InvalidJTIError if not a string |
typ (custom) | Access vs other | your code | InvalidTokenError("not an access token") |
(missing any of require) | options={"require": ...} | MissingRequiredClaimError |
Fix / how to use it: one decode_access_token with all of the above, tested with a token for each failure (the snippet has eight for HS256 and six for the asymmetric verifier); a leeway of seconds, not minutes (30 s here).
Algorithms and keys: HS256, RS256, EdDSA, kid and key rotation Must-know
In plain words: HS256 uses one shared secret key to sign and verify: whoever can verify can also mint tokens. RS256 and EdDSA use a private key to sign and a public key to verify, so other services can check tokens without being able to forge them. kid in the header says which key signed, so you can rotate keys without breaking tokens already issued.
Common misunderstanding: "Read alg from the token header to know how to verify." That is the classic attack: a token with alg: none, or an RS256 public key used as an HS256 secret. The algorithm comes from your configuration or from the key you hold, never from the token.
Definition: RFC 8725 §3.1: "Libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms when performing cryptographic operations. … each key MUST be used with exactly one algorithm". PyJWT enforces the first half with the required algorithms= list and refuses to use a PEM public key as an HMAC secret (InvalidKeyError, tested). EdDSA for JOSE is RFC 8037.
Key rotation with kid (test_eddsa_with_kid_and_rotation, real)
1 ring = {2026-10} sign -> header {"alg":"EdDSA","kid":"2026-10"}
2 ring = {2026-10, 2026-11} new tokens -> kid 2026-11; JWKS publishes both public keys
3 old token (kid 2026-10) -> still verifies while its key is published
4 retire 2026-10 after max token lifetime
5 old token -> InvalidTokenError("unknown kid")| Algorithm | Keys | Verify without minting | Token size | Use when |
|---|---|---|---|---|
| HS256 | One shared secret (≥ 32 bytes) | No | Smallest | One service issues and verifies |
| RS256 | RSA 2048+ private/public | Yes | Signature 256 bytes | Interop with everything (JWKS, OIDC) |
| ES256 | P-256 | Yes | 64-byte signature | Smaller than RSA |
| EdDSA (Ed25519) | Ed25519 | Yes | 64-byte signature | New systems that control both ends |
none | none | n/a | Never |
Fix / how to use it: HS256 with a 64-byte random secret key while one service does everything; EdDSA or RS256 with kid and a published key set as soon as a second service verifies; rotate on a schedule and keep the old public key for one maximum token lifetime. The rest of the header attacks are in JWT Deep Dive.
The current-user dependency: get_current_user with Depends and Security Must-know
In plain words: get_current_user is the one function that turns "a string from a header" into "a User row or a 401". Every protected route asks for it, and the dependency cache runs it once per request.
Common misunderstanding: "Decoding the token is enough." The token can be valid and the user deleted, deactivated, or reset since; the snippet checks all three after the signature.
Definition: FastAPI's tutorial: "get_current_user will have a dependency with the same oauth2_scheme we created before." Security() is Depends() plus scopes; for API keys the snippet uses Security(api_key_header) so the key shows up as a security requirement in OpenAPI.
GET /users/me (dependency graph, resolved per request)
1 oauth2_scheme -> "eyJ..." or 401 Not authenticated
2 get_settings, get_session
3 get_current_claims -> decode_access_token; ExpiredSignatureError -> 401 Token expired
InvalidTokenError -> 401; jti in revoked_access_tokens -> 401
4 get_current_user -> int(sub) or 401; session.get(User, id); inactive -> 401; ver != token_version -> 401
5 me(user) -> 200| Layer | Dependency | Fails with |
|---|---|---|
| Transport | oauth2_scheme | 401 Not authenticated |
| Token | get_current_claims | 401 Token expired / Could not validate credentials |
| Account | get_current_user | 401 |
| Permission | require_role("admin") | 403 |
Fix / how to use it: CurrentUser = Annotated[User, Depends(get_current_user)] once, used everywhere; router-level dependencies=[Depends(require_role("admin"))] for whole groups; never re-implement the check inside a route.
Refresh tokens: rotation and reuse detection Must-know
In plain words: the refresh token is a random string, not a JWT. The server stores its SHA-256 hash with a family id (one family per login). Each use marks it used and returns a new one in the same family. If a used token ever comes back, someone has a copy, so the whole family is revoked and the user logs in again.
Common misunderstanding: "A JWT refresh token makes the server stateless." Rotation, revocation and reuse detection need server-side state whatever the token's format. A JWT-formatted refresh token can support them if the server stores its jti and family and checks them on every use; RFC 9700 even allows encoding the grant in the token ("The grant to which a refresh token belongs may be encoded into the refresh token itself", provided its integrity is ensured, "for example, using signatures"). What does not work is a self-contained JWT refresh token with no server-side record: it cannot be revoked, and a stolen one works until it expires. This chapter uses opaque tokens because the lookup is needed anyway, and the token then carries nothing readable. A second one: "check used_at in Python, then set it". Two concurrent refreshes both see NULL and both succeed; the snippet claims the row with a conditional UPDATE and branches on rowcount (test_two_concurrent_claims_only_one_wins, test_a_rollback_elsewhere_cannot_undo_a_claim).
Definition: RFC 9700 §4.14.2: "Refresh token rotation: the authorization server issues a new refresh token with every access token refresh response. The previous refresh token is invalidated, but information about the relationship is retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach. The authorization server cannot determine which party submitted the invalid refresh token, but it will revoke the active refresh token." And: "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation".
| Event | Row state | Response |
|---|---|---|
| Login | RT1 new, family F | 200, RT1 |
| Refresh with RT1 | RT1 used_at set, RT2 new in F | 200, RT2 |
| Refresh with RT1 again | F all revoked_at | 401 reuse detected |
| Refresh with RT2 | revoked | 401 reuse detected |
| Refresh after 14 days | expired | 401 Refresh token expired |
| Another device (family G) | untouched | 200 (test_reuse_does_not_touch_other_sessions) |
Fix / how to use it: opaque random token, hashed at rest, family id, conditional UPDATE … WHERE used_at IS NULL, revoke the family on reuse, keep access tokens short because revoking the family does not revoke access tokens already issued (they live up to 15 more minutes).
Revocation and logout: denylist and jti store Important
In plain words: a signed access token is valid until exp no matter what. To end it earlier, the server keeps a list of revoked jti values and checks it on every request. Each row can be deleted once its exp has passed, so the list stays small.
Common misunderstanding: "Stateless JWTs mean no database lookup." With a denylist there is a lookup per request (a primary-key read, or a Redis GET); the alternative is to accept that logout takes effect within one access-token lifetime.
Definition: RFC 9700 says authorization servers "MAY revoke refresh tokens automatically in case of a security event, such as: password change or logout at the authorization server." The OWASP JWT cheat sheet: session invalidation "can be achieved using a deny list of revoked sessions/tokens", and then "user sessions won't be completely stateless anymore". The snippet's logout revokes the refresh family and inserts the access token's jti with its exp into revoked_access_tokens; password reset increments users.token_version, and every access token carries the version it was issued with (ver), so every older one fails. An earlier version of the snippet compared a timestamp with iat; because iat has whole-second resolution, a token issued earlier in the same second as the reset survived. A counter has no such boundary (test_reset_cuts_off_access_tokens_issued_in_the_same_second).
| Mechanism | Kills | Cost | Here |
|---|---|---|---|
Short exp | Everything, eventually | None | 15 minutes |
| Refresh family revoke | Future refreshes of one login | One UPDATE | logout, reuse |
jti denylist (jti store) | One access token now | One lookup per request | logout |
Per-user counter (token_version vs ver claim) | All of a user's access tokens | Already loading the user | password reset |
| Key rotation | Every token signed with the old key | Re-login for all | incidents |
Fix / how to use it: short access tokens plus family revocation for normal logout; the jti store when "logout now" is a requirement; the per-user counter for password changes; purge a denylist row only after exp + leeway, because jwt.decode still accepts the token during the leeway: the snippet stores expires_at = exp + leeway_seconds and purge_denylist() deletes rows past it (test_logged_out_token_stays_denied_through_the_leeway_after_a_purge).
Cookie storage, HttpOnly, Secure, SameSite and CSRF Important
In plain words: in a browser, a refresh token in JavaScript-readable storage can be stolen by any XSS. An HttpOnly cookie cannot be read by scripts, Secure keeps it off plain HTTP, SameSite=Strict keeps it off cross-site requests, and Path=/auth keeps it off every other route. But a cookie is sent automatically, so a state-changing request authenticated by a cookie needs a CSRF defence.
Common misunderstanding: "SameSite replaces CSRF tokens." OWASP: "Treat SameSite as defense in depth against CSRF, not as a replacement for a CSRF token." And the naive double submit (random cookie equals header) is "DISCOURAGED": an attacker who can write cookies on the domain plants a matching pair.
Definition: OWASP CSRF cheat sheet, "Signed Double-Submit Cookie (RECOMMENDED)": it "explicitly ties tokens to the user's authenticated session"; "Compute HMAC-SHA-256 over an unambiguous encoding of the session-dependent value and random value … read the token from a submitted header or form field, never from the cookie alone." The snippet's csrf_token_for is nonce.HMAC(secret, len:sha256(refresh_token)|len:nonce). Starlette's set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax", partitioned=False): every safe value is opt-in.
Cookie mode (X-Client: browser), test_cookie_mode_sets_httponly_secure_samesite_and_needs_csrf
1 POST /auth/token -> Set-Cookie: refresh_token=rt_...; HttpOnly; Path=/auth; SameSite=strict; Secure
Set-Cookie: csrf_token=<nonce>.<hmac>; Path=/; SameSite=strict; Secure
2 JS reads csrf_token -> sends X-CSRF-Token: <nonce>.<hmac>
3 POST /auth/refresh -> server recomputes HMAC over the refresh cookie -> 200, both cookies rotated
4 no header / "guess" / planted "attacker.0000" -> 403 CSRF check failed| Storage | XSS can steal | CSRF risk | Fits |
|---|---|---|---|
Authorization header, token in memory | Only while the page runs | None | SPAs (access token), mobile, servers |
localStorage | Yes, permanently | None | Avoid for refresh tokens |
HttpOnly; Secure; SameSite=Strict cookie | No | Yes: add signed double submit | Browser refresh token |
| Server session cookie | No | Yes | Classic web apps (sessions chapter) |
Fix / how to use it: access token in memory and the Authorization header; refresh token in an HttpOnly; Secure; SameSite=Strict; Path=/auth cookie for browsers; a signed, session-bound double-submit token on every cookie-authenticated POST; consider the __Host- prefix when you control the whole domain.
Secrets in settings: SecretStr and pydantic-settings Important
In plain words: the JWT secret key comes from the environment, not the code; it is typed as SecretStr so it prints as stars; and the app refuses to start without it.
Common misunderstanding: "A default value makes local development easier." A default secret key is a secret key every deployment that forgot the variable shares, and anyone who reads the repository can mint tokens.
Definition: Pydantic: SecretStr is "A string used for storing sensitive information that you do not want to be visible in logging or tracebacks. When the secret value is nonempty, it is displayed as '**********' instead of the underlying value in calls to repr() and str()." Equality uses secrets.compare_digest. pydantic-settings reads AUTH_JWT_SECRET because of env_prefix="AUTH_", and .env through env_file. The FastAPI "Settings and Environment Variables" guide shows the same BaseSettings pattern.
| Test (real) | Shows |
|---|---|
test_secret_is_hidden_in_repr_and_dump | str(s.jwt_secret) == "**********"; get_secret_value() is explicit |
test_missing_or_short_secret_refuses_to_start | Field required / at least 32 items |
test_secret_read_from_environment | AUTH_JWT_SECRET wins |
conftest settings fixture | A new secrets.token_urlsafe(48) per test session |
Fix / how to use it: no default; min_length=32; generate with python -c "import secrets; print(secrets.token_urlsafe(64))"; keep .env out of git and ship a .env.example whose placeholder fails validation; in production, read it from the platform's secret store.
User enumeration and the generic error Must-know
In plain words: if "unknown e-mail" and "wrong password" look different (message, status code, or response time), an attacker can test a list of e-mails and learn which are customers. Answer the same bytes after the same amount of work.
Common misunderstanding: "Same message is enough." The before app would leak through timing even with one message: no hash for unknown users means a faster answer. The snippet verifies against DUMMY_HASH (test_unknown_user_still_pays_for_one_argon2_verification). Real medians over 15 requests: 24.6 ms wrong password, 24.4 ms unknown user.
Definition: OWASP Authentication Cheat Sheet: "Using any of the authentication mechanisms (login, password reset, or password recovery), an application must respond with a generic error message regardless of whether" the user ID or password was wrong or the account does not exist, e.g. "Login failed; Invalid user ID or password." The FastAPI JWT tutorial does the dummy-hash verification quoted at the top of this page.
| Endpoint | Leak | Snippet's answer |
|---|---|---|
| Login | message, status, timing | same 401 body and header, dummy hash |
| Login, locked account | "account locked" message | same generic 401 |
| Password reset request | "no such e-mail" | always 202, same text; mail sent after the response |
| Signup | "already registered" | 409 here; OWASP says "the same approach of a generic error message can be applied" to registration |
Fix / how to use it: one constant for the login error; dummy hash for unknown users; constant reset response; for signup, decide consciously (the snippet keeps a 409 for usability and says so in a comment).
Rate limiting login and lockout Important
In plain words: slow hashing makes each guess expensive; rate limits and lockout cap how many guesses there are. Count failures per account (so a botnet with many IPs is still capped) and limit per IP at the edge.
Common misunderstanding: "Lock the account after five failures and say so." That message tells the attacker the account exists, and lets anyone lock any user out. The snippet locks after five failures but keeps the generic 401, and a password reset unlocks.
Definition: OWASP: "The counter of failed logins should be associated with the account itself, rather than the source IP address", with a lockout threshold, a lockout duration, and optionally an exponential lockout. The algorithms (token bucket, sliding window) are in Rate Limiting Algorithms.
| Control | Stops | Side effect |
|---|---|---|
| argon2id cost | Offline cracking speed | CPU and memory per login |
| Per-account counter + lockout | Online guessing on one account | Victim lock-out (DoS); keep it temporary in production |
| Per-IP rate limit (proxy, Redis) | Spraying from few IPs | Shared IPs (NAT) |
| CAPTCHA / MFA after N failures | Bots | Friction |
Fix / how to use it: increment the counter in SQL (failed_logins = failed_logins + 1, so concurrent failures all count); lockout with a duration or exponential backoff in production (the snippet's lockout lasts until a reset, to keep it short); a per-IP limiter in front (Go version).
Password reset: hashed, single-use, expiring token sent by BackgroundTasks Must-know
In plain words: the reset request answers 202 at once and schedules the real work as a background task: look up the user, create a random token, store only its hash with a 15-minute expiry, e-mail the raw token as a link. The confirm step accepts it once, sets the new password, and kills every other reset link and every session.
Common misunderstanding: "Store the token so we can look it up." Store its SHA-256: a database reader must not be able to reset anyone's password. Another: "A fast hash is weak." For 256 random bits it is right; slow hashing is for low-entropy passwords.
Definition: OWASP Forgot Password Cheat Sheet: "Return a consistent message for both existent and non-existent accounts. Ensure that the time taken for the user response message is uniform. … Ensure that generated tokens or codes are: Randomly generated using a cryptographically safe algorithm. Sufficiently long to protect against brute-force attacks. Stored securely. Single use and expire after an appropriate period." FastAPI's background tasks run "after returning a response"; the docs use e-mail notifications as their example.
| Property | How | Test |
|---|---|---|
| Same answer | always 202 + constant text | test_known_and_unknown_email_get_the_same_answer |
| Uniform response timing | BackgroundTasks email: the handler only calls background.add_task(process_reset_request, …); lookup, insert and mail run after the response | test_handler_does_the_same_work_for_both_and_defers_the_lookup |
| Single-use token | conditional UPDATE … used_at | test_reset_token_is_single_use |
| Expiry | expires_at 900 s | test_reset_token_expires |
| Token hashing | sha256_hex | test_reset_token_stored_only_as_hash |
| Sessions killed | refresh tokens revoked, token_version incremented | test_reset_kills_existing_sessions_and_older_reset_links, test_reset_cuts_off_access_tokens_issued_in_the_same_second |
Honest limits of the timing claim: the handler's work is identical for every address, so the time to the 202 does not depend on whether the account exists. The background task still runs in the same worker after the response, so under load a burst of requests for real accounts makes later responses slightly slower; a production system moves process_reset_request to a queue (see Background Tasks). The snippet's tests prove identical bodies, headers and handler work, not equal wall-clock times.
Fix / how to use it: secrets.token_urlsafe(32), hash at rest, 15 to 60 minutes, single use, invalidate siblings, revoke sessions; for real e-mail delivery with retries, a queue rather than BackgroundTasks (see Background Tasks).
API keys for machine clients: APIKeyHeader and API key hashing Important
In plain words: a cron job or a partner's server cannot log in with a password, so it sends a long random key in X-API-Key. The server stores the key's hash and a short public prefix to find the row, shows the full key once, and can revoke it.
Common misunderstanding: "API keys are fine in clear, they are not passwords." A dump of a table of clear keys is a dump of working credentials. Sanctum hashes its tokens with SHA-256 for the same reason.
Definition: FastAPI's APIKeyHeader(name="X-API-Key", auto_error=False) reads the header and adds an apiKey security scheme (real: {"type": "apiKey", "in": "header", "name": "X-API-Key"}). Python hmac docs: use compare_digest() "instead of the == operator to reduce the vulnerability to timing attacks".
Key format and lookup
1 create : prefix = "ak_" + 8 random chars; key = prefix + "." + token_urlsafe(32)
2 store : prefix (clear, unique), sha256(key) -> respond {"api_key": key} once
3 request: X-API-Key: ak_3f9cxk2a.Zq... -> split on "." -> SELECT by prefix
4 check : compare_digest(sha256(key), row.key_hash) -> revoked_at IS NULL -> 200 {"client": name}
5 else : 401 Invalid API key, WWW-Authenticate: APIKey| Choice | Snippet | Why |
|---|---|---|
| Header, not query string | X-API-Key | Query strings end up in logs |
| Hash | SHA-256 | Keys are random; a slow hash would cost every request |
| Prefix | ak_ + 8 chars, clear | Lookup, support, secret-scanning patterns |
| Compare | secrets.compare_digest | Constant time |
| Revoke | revoked_at | Rotation without deleting history |
Fix / how to use it: Security(APIKeyHeader(...)) in a dependency; scope keys to the routes they need; rotate by issuing a new key before revoking the old; HMAC request signing and webhook signatures are in the API-security chapters of system design.
Roles and scopes preview: require_role, Security and SecurityScopes Good to know
In plain words: the access token can carry what the user may do: a role claim here, or OAuth2 scopes. A dependency compares it with what the route needs and answers 403.
Common misunderstanding: "Trust the role in the token forever." A role change takes effect only when the next access token is issued (≤ 15 minutes here) unless you read the role from the database, as the snippet's require_role effectively does via the loaded User.
Definition: The FastAPI reference: "When you need to declare dependencies with OAuth2 scopes you use Security()." A dependency can declare a parameter of type SecurityScopes and read security_scopes.scopes (all the scopes required by the dependants) and security_scopes.scope_str for the WWW-Authenticate header. The full model (RBAC tables, SecurityScopes checks, per-object permissions) is the next chapter, Authorization: RBAC & Scopes.
| Mechanism | Fails with | Where |
|---|---|---|
require_role("admin") on a router | 403 | this snippet |
Security(get_current_user, scopes=["notes:write"]) + SecurityScopes | 401 with scope="..." per the docs | authorization chapter |
| Per-object ownership check | 403 or 404 | authorization chapter |
Fix / how to use it: authenticate in get_current_user, authorise in a separate dependency; attach role checks to routers; read the authoritative role from the database.
Testing auth: dependency_overrides and httpx AsyncClient tests Must-know
In plain words: test the real flow end to end (signup, login, refresh, logout) and test every negative case; for unit tests of other features, replace get_current_user with a fake user via app.dependency_overrides.
Common misunderstanding: "Mock jwt.decode." Then nothing tests your decode options. Override at the dependency boundary instead, and keep the real token code under its own tests. Another: "AsyncClient runs the lifespan." It does not; the FastAPI docs point to asgi-lifespan's LifespanManager, and the snippet enters app.router.lifespan_context(app) directly.
Definition: FastAPI "Testing Dependencies with Overrides"; "Async Tests" with AsyncClient(transport=ASGITransport(app=app), base_url="http://test"). The snippet also overrides get_clock with a FrozenClock, so refresh and reset expiry are tested by moving time, not by sleeping.
| Technique | Test |
|---|---|
dependency_overrides[get_current_user] | test_dependency_override_skips_auth_in_unit_tests |
dependency_overrides[get_clock] | test_expired_refresh_token, test_reset_token_expires |
httpx AsyncClient + ASGITransport | test_signup_login_me_refresh_logout |
| A token per failure mode | test_access_tokens.py (18 collected tests) |
monkeypatch a spy | test_unknown_user_still_pays_for_one_argon2_verification |
| Two sessions, two connections, rollback | test_a_rollback_elsewhere_cannot_undo_a_claim |
| Two threads, one write lock | test_two_concurrent_claims_only_one_wins |
Fix / how to use it: one test per negative case listed in this chapter; a fresh random secret key per test session; never commit a real secret, even in tests.
Mechanics
What happens at login and on every request Important
POST /auth/token, step by step (app/main.py login)
1 FastAPI parses the form (python-multipart) into OAuth2PasswordRequestForm; JSON -> 422
2 len(password) > 128 -> 401 generic error, nothing hashed
SELECT users WHERE email = lower(strip(username))
3 verify_password(pw, hash or None) None -> verify against DUMMY_HASH, return (False, None)
else -> pwdlib verify_and_update -> (ok, new_hash)
4 locked = failed_logins >= 5
5 not ok / unknown / inactive / locked -> UPDATE failed_logins = failed_logins + 1 (if user)
-> 401 "Incorrect email or password", WWW-Authenticate: Bearer
6 new_hash -> store it (verify and rehash); failed_logins = 0
7 INSERT refresh_tokens(sha256(rt), new family_id, expires_at = now + 14 d)
8 JWT = HS256(iss, aud, sub, iat, nbf, exp = now + 900, jti, role, typ="access", ver=token_version)
9 header client -> body {access_token, token_type, expires_in, refresh_token}
browser (X-Client: browser) -> body without refresh_token + two Set-Cookie headersThe refresh-token state machine Important
login
|
v
+------> ACTIVE (used_at NULL, revoked_at NULL, expires_at > now)
| | refresh: conditional UPDATE wins
| v
| USED ---- presented again ----> family -> REVOKED, 401 reuse detected
| |
new row in | (the new row starts ACTIVE)
same family -------+
ACTIVE -- expires_at <= now --> 401 Refresh token expired (row kept)
ACTIVE -- logout / reset ----> REVOKED (presenting it later = reuse path, 401)Check order in /auth/refresh | Why this order |
|---|---|
| 1 CSRF (cookie mode only) | Reject forged browser requests before touching the database |
| 2 Hash lookup | Unknown token: plain 401, nothing to revoke |
3 used_at / revoked_at | Reuse wins over expiry: an old stolen token still burns the family |
4 expires_at | Expired but never reused: 401, no family action |
| 5 User active | Disabled accounts cannot refresh |
6 claim_once | The race: a loser is treated as reuse |
| 7 Issue new row, same family | Rotation |
The tables, as emitted by SQLAlchemy Good to know
The DDL for the two central tables, compiled for PostgreSQL from the snippet's models (real output, runs/ddl-sqlite.txt also has the SQLite form). In a real project this is an Alembic migration:
CREATE TABLE users (
id SERIAL NOT NULL,
email VARCHAR(320) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
role VARCHAR(20) NOT NULL,
is_active BOOLEAN NOT NULL,
failed_logins INTEGER NOT NULL,
token_version INTEGER NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_users_email ON users (email);
CREATE TABLE refresh_tokens (
id SERIAL NOT NULL,
user_id INTEGER NOT NULL,
token_hash VARCHAR(64) NOT NULL,
family_id VARCHAR(32) NOT NULL,
issued_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
used_at TIMESTAMP WITHOUT TIME ZONE,
revoked_at TIMESTAMP WITHOUT TIME ZONE,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES users (id) ON DELETE CASCADE,
UNIQUE (token_hash)
);
CREATE INDEX ix_refresh_tokens_family_id ON refresh_tokens (family_id);
CREATE INDEX ix_refresh_tokens_user_id ON refresh_tokens (user_id);
-- The single-use claim that claim_once() issues (one row or none):
UPDATE refresh_tokens SET used_at = :now
WHERE id = :id AND used_at IS NULL AND revoked_at IS NULL;| Index | Serves |
|---|---|
UNIQUE (token_hash) | The lookup on every refresh, and a collision guard |
ix_refresh_tokens_family_id | Revoking a family |
ix_refresh_tokens_user_id | Revoking every session at reset |
ix_users_email (unique) | Login and signup; store e-mails lower-cased |
Exact errors, warnings and outputs Must-know
| Trigger | Exact text (real run) |
|---|---|
No Authorization header | 401 {"detail":"Not authenticated"} + www-authenticate: Bearer |
| Expired token | 401 {"detail":"Token expired"} |
Tampered, foreign key, alg: none, refresh token as access token | 401 {"detail":"Could not validate credentials"} |
| Wrong password / unknown user | 401 {"detail":"Incorrect email or password"} (content-length 40 both) |
| Reused refresh token | 401 {"detail":"Refresh token reuse detected"} |
| Admin route as a user | 403 {"detail":"Forbidden"} |
| Bad API key | 401 {"detail":"Invalid API key"} + www-authenticate: APIKey |
| Missing secret key | ValidationError … jwt_secret Field required [type=missing, …] |
| Short secret key | Value should have at least 32 items after validation, not 9 [type=too_short, input_value='CHANGE-ME', …] |
| Short HMAC key in PyJWT 2.11+ | InsecureKeyLengthWarning: The HMAC key is 6 bytes long, which is below the minimum recommended length of 32 bytes for SHA256. |
jwt.encode(..., pem_public_key, algorithm="HS256") | jwt.InvalidKeyError (PyJWT refuses PEM keys as HMAC secrets) |
Forged alg: HS256 header against an RSA key | jwt.InvalidAlgorithmError |
Solving the classic problems
| Problem | Symptom | Fix in the snippet |
|---|---|---|
| Plain or fast password hashes | A dump cracks in hours | argon2id via pwdlib |
| Old bcrypt hashes after a migration | Mixed hashes forever | verify_and_update rehash on login |
| Tokens that never expire | Stolen token works for months | exp 15 min, require |
Algorithm confusion, alg: none | Forged tokens accepted | fixed algorithms=[...] list |
| Token for another service accepted | Cross-service replay | aud, iss |
| Logout does nothing | Copied token still works | family revoke + jti denylist |
| Stolen refresh token | Silent long-term access | rotation + reuse detection |
| Concurrent refresh double-spend | Two valid successors | conditional UPDATE |
| Enumeration | Attacker learns customer list | generic error + dummy hash + constant reset reply |
| Brute force | Password spraying | account counter, lockout, edge rate limit |
| Reset link reused or leaked from DB | Account takeover | hashed, single-use, expiring token |
| Secret in git | Anyone mints tokens | SecretStr, env, no default |
| XSS steals refresh token | Session hijack | HttpOnly cookie + signed double submit |
One check for every protected route
CurrentUser everywhere, require_role on routers. A route that forgets its dependency is public, so put the dependency on the router (APIRouter(dependencies=[...])) for groups that must never be public.
Detecting a stolen refresh token
Rotation alone limits a stolen token to one use; reuse detection turns that one use into an alarm. Log the reuse event with the family id and user id, and alert on spikes.
Password migrations without a reset campaign
Import the old hashes as they are (bcrypt from Laravel: pwdlib's bcrypt identifier matches 2[abxy], so $2y$ is accepted; a $2y$ hash verified and was upgraded to argon2id in runs/probe-timing-bcrypt-settings.txt), add the matching hasher after argon2 in the tuple, and let verify_and_update move users over as they log in.
Reset links that cannot be replayed
Hash, expiry, single use via conditional UPDATE, invalidate siblings, revoke sessions, cut off access tokens. Six lines in password_reset_confirm, six tests.
Choosing
| Question | Choose | Over | When the other wins |
|---|---|---|---|
| Access token format | JWT | Opaque + introspection | You need instant revocation everywhere without a denylist |
| Refresh token format | Opaque, hashed in DB | JWT with a server-side jti/family record | Several services must read the grant from the token itself; a JWT with no server record: never |
| Signing | HS256 | RS256 / EdDSA | More than one service verifies: EdDSA or RS256 |
| Hash | argon2id | bcrypt | Platform without argon2; FIPS: PBKDF2 |
| JWT library | PyJWT | python-jose | You need JWE: joserfc / authlib |
| Browser storage | HttpOnly cookie for the refresh token | localStorage | Never localStorage for refresh tokens |
| Server-rendered web app | Server sessions | JWTs | Separate API consumers |
| Machine clients | API key (hashed) | Password login | Third-party clients: OAuth2 client credentials |
| Third-party login, SSO | OIDC code flow (chapter) | Password form | Your own first-party app only |
| Build or buy | This chapter | An identity provider | Many apps, SSO, compliance: buy (Keycloak, Auth0, Cognito …) |
JWT access tokens vs sessions
| JWT access token + refresh | Server session cookie | |
|---|---|---|
| Check per request | Signature + optional denylist | Session store lookup |
| Logout | Revoke family; denylist (kept until exp + leeway) for instant | Delete row |
| Works across services | Yes (public key) | Needs shared store |
| Browser CSRF | None with headers | Needs CSRF defence |
| Size | ~300+ bytes per request | ~40 bytes |
In architecture: from a single process to a distributed system
Monolith: one process, one database
This chapter's snippet is the monolith shape: one FastAPI app issues and verifies its own HS256 tokens, the refresh, reset, API-key and denylist tables sit next to users in the same database, and one get_current_user guards every router. A shop backend has its customer login, an admin router behind require_role("admin"), an API key for the warehouse integration, and password reset mails through a background task. Nothing needs a public key yet.
Modular monolith and multiple databases
Move authentication into its own module (app/auth/) with its own tables and expose only CurrentUser, require_role and get_api_client to the rest. If the auth tables live in another database, get_current_user still loads the user from there; the other modules never touch password hashes.
Microservices
One auth service issues tokens; every other service only verifies. Switch to EdDSA or RS256 with kid, publish the public keys as a JWKS endpoint, and let services cache it. Each service checks aud equal to its own name, so a token for the notes API is useless at billing. Refresh tokens, reset tokens and passwords never leave the auth service. Service-to-service calls use their own credentials (client credentials or mTLS), not forwarded user passwords. Most teams at this point consider an identity provider (OAuth 2.0, OIDC & SSO).
Distributed data: replicas, caches, sharded databases, multi-region
Refresh rotation and reset single use are writes with a condition: they must hit the primary, never a read replica, or two regions can both "win". The jti denylist is read on every request: put it in Redis with a TTL equal to the token's remaining lifetime plus the leeway (exp - now + leeway), and accept that a cache outage either fails closed (401s) or open (logout lag); decide which. Keys: the JWKS can be cached at every edge; private keys stay in one KMS or secret store. Multi-region: issue tokens in one region per user, or make the refresh family's state replicated with strong consistency.
Scaling path: 1×, 10×, 100×
| Scale | Bottleneck | Move |
|---|---|---|
| 1× | None: ~25 ms argon2id per login | The snippet as is |
| 10× | Login CPU and memory (64 MiB per concurrent argon2id hash) | Size workers for concurrent logins, rate limit login, keep hashing in the thread pool (def routes) |
| 10× | Denylist lookups | Redis with TTL; purge job for the SQL table |
| 100× | Token issuance in one place, key distribution | Dedicated auth service or IdP, EdDSA + JWKS, kid rotation |
| 100× | Refresh writes | Partition refresh tokens by user, primary-only writes |
Lab
Every command below ran on the build machine (CPython 3.9.6, macOS, uv 0.13.10, jq) as one script, pipeline/sources/fastapi-authentication-jwt/runs/lab.sh. The output is pasted unchanged from runs/lab-run.txt. The run used a copy of the snippet directory, so no venv, .env or database file lands in the repository; do the same, or point VENV and LABDB outside it.
1. Install and run the tests (real)
cd docs/snippets/python/fastapi-authentication-jwt
export VENV=$HOME/.venvs/auth-lab # any path outside the repository
export LABDB=$HOME/.venvs/auth-lab.db
uv venv -q -p python3 "$VENV"
uv pip install -q -p "$VENV/bin/python" '.[test]'
source "$VENV/bin/activate"
python -m pytest -p no:randomly 2>&1 | tail -1
# 65 passed, 2 warnings in 4.04sThe two warnings are the InsecureKeyLengthWarnings from the before app's deliberately short keys. The 65 tests: test_access_tokens.py 18 (13 functions, one parametrised six ways), test_async_flow.py 1, test_authz_apikeys.py 4, test_login.py 11, test_refresh.py 13, test_reset.py 8, test_settings_before.py 10.
2. Start the server in the background and log in (real)
export AUTH_JWT_SECRET=$(python -c "import secrets; print(secrets.token_urlsafe(48))")
export AUTH_DATABASE_URL="sqlite+pysqlite:///$LABDB"
uvicorn --factory app.main:create_app --port 18934 > uvicorn.log 2>&1 &
SERVER=$!
until curl -s -o /dev/null http://127.0.0.1:18934/docs; do sleep 0.2; done
B=http://127.0.0.1:18934
curl -s -X POST $B/auth/signup -H 'Content-Type: application/json' \
-d '{"email":"alice@example.test","password":"correct horse battery staple"}'; echo
# {"id":1,"email":"alice@example.test","role":"user"}
TOKENS=$(curl -s -X POST $B/auth/token -d username=alice@example.test -d 'password=correct horse battery staple')
ACCESS=$(echo "$TOKENS" | jq -r .access_token)
REFRESH=$(echo "$TOKENS" | jq -r .refresh_token)
echo "$TOKENS" | jq -c '{token_type, expires_in, access: (.access_token[0:20] + "..."), refresh: (.refresh_token[0:6] + "...")}'
# {"token_type":"bearer","expires_in":900,"access":"eyJhbGciOiJIUzI1NiIs...","refresh":"rt_qgj..."}
# look at the claims (decoding is not verifying: anyone can do this)
echo "$ACCESS" | cut -d. -f2 | python -c "import sys,base64,json; p=sys.stdin.read().strip(); c=json.loads(base64.urlsafe_b64decode(p+'='*(-len(p)%4))); print(sorted(c), 'exp-iat =', c['exp']-c['iat'])"
# ['aud', 'exp', 'iat', 'iss', 'jti', 'nbf', 'role', 'sub', 'typ', 'ver'] exp-iat = 900
curl -s -w ' %{http_code}\n' $B/users/me -H "Authorization: Bearer $ACCESS"
# {"id":1,"email":"alice@example.test","role":"user"} 200
curl -s -D - -o /dev/null $B/users/me | grep -i -E '^HTTP|^www-authenticate'
# HTTP/1.1 401 Unauthorized
# www-authenticate: Bearer3. Attack your own login (real)
curl -s -w ' %{http_code}\n' -X POST $B/auth/token -d username=alice@example.test -d password=nope
# {"detail":"Incorrect email or password"} 401
curl -s -w ' %{http_code}\n' -X POST $B/auth/token -d username=nobody@example.test -d password=nope
# {"detail":"Incorrect email or password"} 401The timing side was measured separately with TestClient (runs/probe-timing-bcrypt-settings.txt): medians over 15 requests were 24.6 ms for the wrong password and 24.4 ms for the unknown user; the before app answered in 0.39 ms and 0.38 ms, with 401 vs 404.
4. Steal a refresh token, and the other negatives (real)
NEW=$(curl -s -X POST $B/auth/refresh -H 'Content-Type: application/json' -d "{\"refresh_token\":\"$REFRESH\"}")
NEW_REFRESH=$(echo "$NEW" | jq -r .refresh_token)
[ "$NEW_REFRESH" != "$REFRESH" ] && echo "rotated: yes"
# rotated: yes
curl -s -w ' %{http_code}\n' -X POST $B/auth/refresh -H 'Content-Type: application/json' -d "{\"refresh_token\":\"$REFRESH\"}"
# {"detail":"Refresh token reuse detected"} 401 <- the replayed, already-used token
curl -s -w ' %{http_code}\n' -X POST $B/auth/refresh -H 'Content-Type: application/json' -d "{\"refresh_token\":\"$NEW_REFRESH\"}"
# {"detail":"Refresh token reuse detected"} 401 <- the family is revoked: log in again
curl -s -w ' %{http_code}\n' -X POST $B/auth/password-reset/request -H 'Content-Type: application/json' -d '{"email":"alice@example.test"}'
# {"detail":"If that address is registered, a reset link has been sent."} 202
curl -s -w ' %{http_code}\n' -X POST $B/auth/password-reset/request -H 'Content-Type: application/json' -d '{"email":"nobody@example.test"}'
# {"detail":"If that address is registered, a reset link has been sent."} 202
curl -s -w ' %{http_code}\n' $B/admin/stats -H "Authorization: Bearer $ACCESS"
# {"detail":"Forbidden"} 403
curl -s -w ' %{http_code}\n' $B/machine/ping -H 'X-API-Key: ak_nope.nope'
# {"detail":"Invalid API key"} 4015. What Swagger's Authorize button reads, then stop the server (real)
curl -s $B/openapi.json | jq -c .components.securitySchemes
# {"OAuth2PasswordBearer":{"type":"oauth2","flows":{"password":{"scopes":{},"tokenUrl":"auth/token"}}},"APIKeyHeader":{"type":"apiKey","in":"header","name":"X-API-Key"}}
curl -s -o /dev/null -w 'GET /docs %{http_code}\n' $B/docs
# GET /docs 200
kill $SERVERIn a browser, http://127.0.0.1:18934/docs shows the Authorize button; entering the e-mail as username and the password makes Swagger post the form to auth/token and send the token on every "Try it out" (the clicks themselves were not run on the build machine; the schema and the GET /docs 200, also in runs/uvicorn.log, are real).
6. Exercises (expected, not run)
- Switch
jwt_algorithmto EdDSA usingapp/keys.py, publish/.well-known/jwks.jsonwithjwt.PyJWK/jwt.algorithms.OKPAlgorithm.to_jwk, and verify a token from a second process that holds only the public key. - Replace the permanent lockout with an exponential one (
locked_until), and add a test that moves the frozen clock. - Move the denylist to Redis with
SET jti 1 EX <seconds to exp + leeway>; expected: the same tests pass with a Redis fixture.
For PHP/Laravel developers
Laravel ships the pieces this chapter builds by hand. Sanctum issues personal access tokens (opaque, "hashed using SHA-256 hashing before being stored in your database") and does cookie-session auth for first-party SPAs; "By default, Sanctum tokens never expire and may only be invalidated by revoking the token." Passport is a full OAuth2 server (built on league/oauth2-server, see JWT Deep Dive) with access and refresh tokens; it issues "long-lived access tokens that expire after one year" by default, and says of the password grant: "We no longer recommend using password grant tokens." Fortify is "a frontend agnostic authentication backend implementation" that registers login, registration, password reset and two-factor routes. The Hash facade defaults to bcrypt ('rounds' => 12) with argon/argon2id drivers and Hash::needsRehash, and the password broker's reset tokens 'expire' => 60 minutes with 'throttle' => 60 seconds.
// Login + token (Sanctum) and verify-and-rehash, the Laravel way
public function login(Request $request)
{
$user = User::where('email', strtolower($request->email))->first();
// Hash::check on a dummy hash for unknown users keeps the timing equal, as in the FastAPI snippet
if (! Hash::check($request->password, $user?->password ?? self::DUMMY_HASH)) {
throw ValidationException::withMessages(['email' => 'Incorrect email or password']); // one generic message
}
if (Hash::needsRehash($user->password)) {
$user->forceFill(['password' => Hash::make($request->password)])->save();
}
$token = $user->createToken('mobile', ['notes:read'])->plainTextToken; // stored as SHA-256
return ['token' => $token];
}
// Reset: $status = Password::sendResetLink($request->only('email')); the docs compare it with
// Password::ResetLinkSent. Do not echo a different status to the client for unknown e-mails.| This chapter (FastAPI) | Laravel |
|---|---|
pwdlib argon2id, verify_and_update | Hash::make (bcrypt by default), Hash::needsRehash |
OAuth2PasswordBearer + get_current_user | auth:sanctum middleware, $request->user() |
| PyJWT access token, 15 min | Passport access token (1 year by default) or Sanctum opaque token |
| Hashed refresh tokens with rotation | Passport refresh tokens (refreshTokensExpireIn); Sanctum has none |
jti denylist / family revoke | $token->revoke() (Passport), $user->tokens()->delete() (Sanctum) |
API key, hashed, APIKeyHeader | Sanctum personal access tokens with abilities |
| Password reset table, single use | password_reset_tokens + Password broker, expire 60 |
| Signed double-submit CSRF | Sanctum SPA auth: session cookie + XSRF token (axios.defaults.withXSRFToken = true) |
| Lockout counter | Fortify's login limiter (fortify.limiters.login, EnsureLoginIsNotThrottled) |
require_role | Gates and policies (authorization chapter) |
The Go angle
In Go the same service is golang.org/x/crypto/bcrypt (or x/crypto/argon2) plus github.com/golang-jwt/jwt/v5, whose parser options mirror PyJWT's arguments. bcrypt in Go refuses long passwords instead of truncating: ErrPasswordTooLong "is returned when the password passed to GenerateFromPassword is too long (i.e. > 72 bytes)", and DefaultCost is 10. The full Go chapter is Authentication in Go.
// bcrypt Go + golang-jwt v5: the decode options of this chapter, one to one
hash, err := bcrypt.GenerateFromPassword([]byte(pw), 12) // ErrPasswordTooLong above 72 bytes
if err := bcrypt.CompareHashAndPassword(hash, []byte(attempt)); err != nil {
return errGeneric // same error for unknown users: compare against a dummy hash first
}
claims := jwt.RegisteredClaims{}
_, err = jwt.ParseWithClaims(tokenString, &claims,
func(t *jwt.Token) (any, error) { return secret, nil },
jwt.WithValidMethods([]string{"HS256"}), // algorithms=["HS256"]
jwt.WithAudience("notes-api"), // audience=
jwt.WithIssuer("https://auth.example.test"),
jwt.WithLeeway(30*time.Second), // leeway=30
jwt.WithExpirationRequired(), // options={"require": ["exp", ...]}
jwt.WithIssuedAt(),
)| FastAPI / Python | Go |
|---|---|
pwdlib argon2id | argon2.IDKey(password, salt, time, memory, threads, keyLen) from x/crypto/argon2 (you write the $argon2id$ encoding) or bcrypt |
| bcrypt 4.3.0 truncates at 72 bytes | ErrPasswordTooLong |
jwt.decode(algorithms=[...]) | jwt.WithValidMethods |
audience=, issuer=, leeway= | WithAudience, WithIssuer, WithLeeway |
options={"require": ["exp"]} | WithExpirationRequired() |
OAuth2PasswordBearer + Depends | middleware reading Authorization, user in context.Context |
secrets.token_urlsafe(32) | crypto/rand.Read + base64.RawURLEncoding (URLEncoding.WithPadding(NoPadding)) |
secrets.compare_digest | crypto/subtle.ConstantTimeCompare |
dependency_overrides | inject a fake UserStore interface |
Common misconceptions
| Belief | Reality |
|---|---|
| A JWT is encrypted | It is signed; anyone can read the claims (the lab decodes one) |
OAuth2PasswordBearer validates tokens | It returns the header's string; get_current_user validates |
jwt.decode checks everything | iss only with issuer=; exp/nbf only if present; claims only required if listed in require |
Read alg from the header | Fix the list; RFC 8725 §3.1 |
| Logout invalidates the JWT | Only with a denylist or a per-user version counter; otherwise it lives until exp (+ leeway) |
| JWT refresh tokens make the server stateless | Rotation and reuse detection need a server record in any format; opaque, hashed, family-tracked is the simplest |
Checking used_at in Python makes a token single use | Only a conditional UPDATE does, under concurrency |
| SHA-256 is fine for passwords | Too fast; fine only for random tokens and API keys |
| passlib is the standard | The original line stopped at 1.7.4 (2020) and breaks on 3.13; the fork is back as 1.9.5 for 3.11+; FastAPI uses pwdlib |
| python-jose is what FastAPI uses | Since 0.111.1 the docs use PyJWT; python-jose had two 2024 CVEs |
| Same error message stops enumeration | Timing too: dummy-hash verification |
| A 403 for a bad token | 401 + WWW-Authenticate; 403 is for authenticated-but-forbidden |
SameSite makes CSRF tokens unnecessary | Defence in depth only (OWASP) |
| Naive double submit is enough | OWASP marks it DISCOURAGED; sign and bind it |
SecretStr hides the secret everywhere | Not in ValidationError input values, and not after get_secret_value() |
| HS256 is insecure | It is fine with a 32+ byte secret when one service signs and verifies |
| Lockout should say "account locked" | That confirms the account exists |
AsyncClient runs the lifespan | It does not; use LifespanManager or the lifespan context |
Cheat sheet
| Topic | Remember |
|---|---|
| Hash | PasswordHash((Argon2Hasher(), BcryptHasher())), verify_and_update |
| Unknown user | verify against DUMMY_HASH, same 401 |
| Login form | Annotated[OAuth2PasswordRequestForm, Depends()], needs python-multipart |
| Bearer | OAuth2PasswordBearer(tokenUrl="auth/token") |
| Encode | iss aud sub(str) iat nbf exp jti, jwt.encode(claims, key, algorithm="HS256") |
| Decode | algorithms=[...], audience=, issuer=, leeway=30, options={"require": [...]} |
| 401 | headers={"WWW-Authenticate": "Bearer"} every time |
| 403 | authenticated but not allowed |
| Refresh | opaque, SHA-256 at rest, family id, rotate, reuse → revoke family |
| Single use | UPDATE … WHERE used_at IS NULL, check rowcount == 1 |
| Logout | revoke family + jti denylist until exp |
| Reset | token_urlsafe(32), hash, 15 min, single use, revoke sessions, same 202 |
background.add_task(send_reset_email, …) | |
| API key | prefix + random, store hash, Security(APIKeyHeader(name="X-API-Key")) |
| Cookies | HttpOnly; Secure; SameSite=Strict; Path=/auth + signed double submit |
| Secrets | SecretStr, pydantic-settings, no default, min_length=32 |
| Compare | secrets.compare_digest |
| Tests | dependency_overrides[get_current_user], frozen clock, httpx AsyncClient |
| Keys | HS256 for one service; EdDSA/RS256 + kid + JWKS for many |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Walk through what happens when a client calls GET /users/me with a Bearer token in this chapter's app. Must-know
Answer
Answer: oauth2_scheme reads Authorization: Bearer … and returns the string (no header: 401 Not authenticated with WWW-Authenticate: Bearer). get_current_claims calls jwt.decode with algorithms=["HS256"], the audience, the issuer, a 30 s leeway and a require list; an expired token gives 401 Token expired, anything else invalid gives 401 Could not validate credentials; then it checks typ == "access" and the jti denylist. get_current_user loads the user by sub, returns 401 for a non-integer sub, rejects inactive users, and rejects tokens whose ver no longer matches users.token_version. The route gets the User. See the current-user dependency.
2 — How should passwords be stored, and how do you move old bcrypt hashes to argon2id without a reset campaign? Must-know
Answer
Answer: As argon2id hashes with a per-password random salt and a work factor measured on your hardware (OWASP minimum m=19 MiB, t=2, p=1; argon2-cffi defaults m=64 MiB, t=3, p=4). With pwdlib, put Argon2Hasher() first and BcryptHasher() second, and call verify_and_update at login: when a bcrypt hash verifies it returns a new argon2id hash, which you store. Users migrate as they log in; the snippet's test_legacy_bcrypt_hash_verifies_and_is_upgraded_to_argon2id proves it. See verify and rehash.
3 — Why is the login response for an unknown e-mail identical to the one for a wrong password, and what else must be identical? Must-know
Answer
Answer: To prevent user enumeration: different status codes, messages or timings let an attacker learn which e-mails have accounts. The body, status and headers are the same constant 401, and the work is the same: an unknown user is verified against a dummy argon2id hash (real medians 24.6 ms vs 24.4 ms). Locked accounts give the same 401 too, and the reset request always answers 202 with the same text, sending the mail from a background task after the response; the handler does the same work for every address. See user enumeration.
4 — 401 or 403: which for a missing token, an expired token, and a valid token without the admin role? Must-know
Answer
Answer: Missing and expired tokens are 401 with WWW-Authenticate: Bearer (RFC 6750: invalid_token → 401); the client should log in or refresh. A valid token without the role is 403 (insufficient_scope → 403), without WWW-Authenticate, because authenticating again will not help. FastAPI's own security classes switched missing credentials from 403 to 401 in 0.122.0. See status codes.
5 — Explain refresh token rotation with reuse detection, and why the legitimate user is logged out too. Must-know
Answer
Answer: Every refresh marks the presented token used and returns a new one in the same family. If a used token is presented again, either the client or an attacker has a copy, and the server cannot tell which. RFC 9700 §4.14.2: it "will revoke the active refresh token", forcing the legitimate client to log in again. That ends the attacker's access at the price of one re-login. The snippet revokes the whole family and leaves other devices' families alone. See refresh tokens.
6 — Two refresh requests with the same token arrive at the same millisecond. What goes wrong with a naive implementation, and what is the fix? Important
Answer
Answer: Read-then-set (if row.used_at is None: row.used_at = now) lets both requests read NULL and both issue a successor: two valid tokens from one. Make the claim one conditional statement, UPDATE refresh_tokens SET used_at = :now WHERE id = :id AND used_at IS NULL AND revoked_at IS NULL, and continue only if rowcount == 1; the loser is treated as reuse. The same applies to reset tokens and to the failed-login counter (failed_logins = failed_logins + 1 in SQL). See test_two_concurrent_claims_only_one_wins. The claim is only atomic per transaction if every request has its own connection: an earlier version of the snippet shared one SQLite connection (StaticPool), and a rollback in one session could undo another session's claim. The snippet now refuses :memory: and uses a file database, where each Session has its own connection (test_a_rollback_elsewhere_cannot_undo_a_claim).
7 — Why choose PyJWT over python-jose, and which decode arguments are mandatory? Important
Answer
Answer: python-jose went from 3.3.0 (June 2021) to 3.4.0 (February 2025) without a release while CVE-2024-33663 (algorithm confusion with OpenSSH ECDSA keys) and CVE-2024-33664 (JWE decompression DoS) were open; the FastAPI docs moved to PyJWT in 0.111.1. With PyJWT always pass algorithms=[...] (a fixed list), audience= and issuer= (without issuer= the issuer is never checked; a token carrying aud fails without audience=), a small leeway, and options={"require": [...]} so a token without exp fails. Use 2.10.1 or later (iss partial-match fix). See JWT libraries.
8 — How does logout work when access tokens are stateless JWTs? Important
Answer
Answer: Three layers. Revoke the refresh token's family so no new access token can be obtained. Put the current access token's jti in a denylist (a table or Redis key) until its exp plus the leeway, checked by get_current_user, if logout must take effect immediately. And keep access tokens short (15 minutes), which bounds the damage of anything you did not revoke. For password changes, a per-user token_version counter (copied into each token as ver) kills every older access token at once, even one issued in the same second. See revocation.
9 — Where should a browser app keep the refresh token, and what does that force you to add? Important
Answer
Answer: In an HttpOnly; Secure; SameSite=Strict cookie scoped to Path=/auth, so scripts (and XSS) cannot read it and it is only sent to the refresh and logout routes. Because the browser sends cookies automatically, the refresh endpoint now needs CSRF protection: the snippet uses OWASP's signed double submit, an HMAC over the refresh token and a nonce, read from the X-CSRF-Token header and recomputed on the server; a planted cookie pair fails. SameSite is defence in depth, not a replacement. See cookies and CSRF.
10 — Design a password reset flow. What are the properties of the token? Important
Answer
Answer: Request: always answer 202 with the same text and schedule one background task for every address; the task looks the user up and, if it exists, creates secrets.token_urlsafe(32), stores its SHA-256 with a 15-minute expiry and e-mails the raw token, all after the response. Confirm: look up the hash, check expiry, claim it with a conditional UPDATE (single use), set the new argon2id hash, mark every other reset token used, revoke all refresh tokens and increment token_version so every older access token fails. The token is random, long, hashed at rest, single use and short-lived, as the OWASP Forgot Password cheat sheet lists. See password reset.
11 — When do you move from HS256 to EdDSA or RS256, and how do you rotate keys? Good to know
Answer
Answer: When a second service must verify tokens: with HS256 every verifier holds the secret key and could mint tokens. With EdDSA or RS256 only the issuer holds the private key; verifiers fetch public keys (JWKS). Rotation: add a new key, sign new tokens with its kid, keep publishing the old public key for one maximum token lifetime, then retire it; verifiers pick the key by kid and the algorithm from the key type, never from the header. See algorithms and keys and test_eddsa_with_kid_and_rotation.
12 — How do Laravel Sanctum, Passport and Fortify map onto this chapter, and what does Go use? Good to know
Answer
Answer: Sanctum is the API-key / personal-token part (opaque tokens hashed with SHA-256, abilities, no expiry by default) plus cookie auth for first-party SPAs. Passport is the OAuth2 server with access and refresh tokens (one-year access tokens by default; password grant no longer recommended). Fortify is the headless login/registration/reset/2FA backend. Go uses golang.org/x/crypto/bcrypt (ErrPasswordTooLong over 72 bytes, DefaultCost 10) and golang-jwt/jwt/v5 with WithValidMethods, WithAudience, WithIssuer, WithLeeway and WithExpirationRequired. See For PHP/Laravel developers and The Go angle.
Glossary
| Term | Meaning |
|---|---|
| Access token | Short-lived credential sent with every request; here a JWT, 15 minutes |
| API key hashing | Storing only sha256(key) plus a clear prefix for lookup |
| API key | Long-lived random secret for a machine client; stored hashed |
APIKeyHeader | FastAPI security class that reads an API key from a named header (X-API-Key here) and declares an apiKey scheme |
| argon2id | Memory-hard password hash, the Argon2 variant OWASP recommends |
aud | Audience claim: who the token is for |
| Authorization code grant + PKCE | The OAuth2 flow RFC 9700 recommends instead of the password grant |
| Authorization header | Authorization: Bearer <token>; where OAuth2PasswordBearer looks |
BackgroundTasks | FastAPI's after-the-response task list; runs the reset lookup and e-mail here |
| bcrypt | Adaptive password hash from 1999; 72-byte input limit |
| Bearer token | A token whose holder is authorised; no proof of possession |
claim_once | The snippet's atomic single-use step: a conditional UPDATE checked by rowcount |
| Clock skew | Difference between server clocks; absorbed by leeway |
| CSRF | A forged cross-site request that rides on the victim's cookies |
| Denylist | Revoked token ids kept until their expiry |
dependency_overrides | app.dependency_overrides[dep] = fake: replaces a dependency in tests |
| Double submit | CSRF defence: a token in a cookie echoed in a header; sign and bind it |
| EdDSA | Edwards-curve signatures (Ed25519) in JOSE, RFC 8037 |
exp | Expiration time claim |
| Family | All refresh tokens descending from one login |
| Fortify | Laravel's headless authentication backend (login, registration, reset, 2FA) |
| Generic error | One message for every login failure |
get_current_user | The dependency that turns a token into a user or a 401 |
| HS256 | HMAC-SHA-256 signature with a shared secret key |
| HttpOnly | Cookie attribute: not readable from JavaScript |
iat | Issued-at claim |
iss | Issuer claim |
jti | JWT ID claim; the key of the denylist (jti store) |
| JWKS | A published set of public keys, selected by kid |
| JWT | JSON Web Token, RFC 7519 |
| Key rotation | Introducing a new signing key while old tokens expire |
kid | Key ID header: which key signed the token |
| Leeway | Seconds of tolerance on exp/nbf/iat checks |
| Lockout | Refusing logins for an account after repeated failures |
nbf | Not-before claim |
OAuth2PasswordBearer | FastAPI security class that reads the Bearer token and declares the password flow |
OAuth2PasswordRequestForm | The username/password login form dependency |
| passlib | The older Python hashing framework; original line stopped at 1.7.4 (2020), fork published as 1.9.5 (2026) |
| Passport | Laravel's OAuth2 server package (access and refresh tokens) |
| Password grant (ROPC) | OAuth2's resource owner password credentials grant; "MUST NOT be used" (RFC 9700 §2.4) |
| pwdlib | Modern password-hashing wrapper (argon2, bcrypt) used by the FastAPI docs |
| pydantic-settings | Package with BaseSettings: typed settings from environment variables and .env |
| PyJWT | The JWT library this chapter uses |
| python-jose | Older JOSE library; CVE-2024-33663 and CVE-2024-33664, fixed in 3.4.0 |
| Refresh rotation | Issuing a new refresh token on every use and invalidating the old one |
| Refresh token | Long-lived credential exchanged for new access tokens; opaque here |
| Reset token | Single-use, expiring secret mailed for a password reset |
| Reuse detection | Treating a used refresh token's return as theft |
| RS256 | RSA PKCS#1 v1.5 signature with SHA-256 |
| Salt | Random per-password input that makes equal passwords hash differently |
| SameSite | Cookie attribute limiting cross-site sending |
| Sanctum | Laravel's API-token (SHA-256-hashed) and SPA cookie authentication package |
secrets.compare_digest | Constant-time comparison of two strings or byte strings |
SecretStr | Pydantic type that hides its value in repr/str |
SecurityScopes | FastAPI parameter listing the scopes the dependants require |
sub | Subject claim: the user id, a string |
| Swagger Authorize | The /docs button that posts to tokenUrl and sends the token on every call |
| Token revocation | Ending a token before its expiry |
token_version | Per-user counter copied into each access token as ver; a reset increments it |
tokenUrl | The OAuth2PasswordBearer argument naming the login route in the OpenAPI schema |
| User enumeration | Learning which accounts exist from differing responses |
| Work factor | The tunable cost of a password hash |
WWW-Authenticate | Response header that tells a 401's client how to authenticate |
References
- FastAPI, "Security" (intro): https://fastapi.tiangolo.com/tutorial/security/
- FastAPI, "Security - First Steps": https://fastapi.tiangolo.com/tutorial/security/first-steps/
- FastAPI, "Get Current User": https://fastapi.tiangolo.com/tutorial/security/get-current-user/
- FastAPI, "Simple OAuth2 with Password and Bearer": https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/
- FastAPI, "OAuth2 with Password (and hashing), Bearer with JWT tokens": https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/
- FastAPI, "OAuth2 scopes": https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/
- FastAPI, "HTTP Basic Auth" (timing attacks,
compare_digest): https://fastapi.tiangolo.com/advanced/security/http-basic-auth/ - FastAPI reference, "Security Tools": https://fastapi.tiangolo.com/reference/security/
- FastAPI, "Background Tasks": https://fastapi.tiangolo.com/tutorial/background-tasks/
- FastAPI, "Settings and Environment Variables": https://fastapi.tiangolo.com/advanced/settings/
- FastAPI, "Testing Dependencies with Overrides": https://fastapi.tiangolo.com/advanced/testing-dependencies/
- FastAPI, "Async Tests": https://fastapi.tiangolo.com/advanced/async-tests/
- FastAPI, "Response Cookies": https://fastapi.tiangolo.com/advanced/response-cookies/
- FastAPI release notes: https://fastapi.tiangolo.com/release-notes/
- FastAPI PR #13917 (pwdlib with Argon2): https://github.com/fastapi/fastapi/pull/13917
- FastAPI discussion #11773 (passlib maintenance): https://github.com/fastapi/fastapi/discussions/11773
- PyJWT, Usage: https://pyjwt.readthedocs.io/en/stable/usage.html
- PyJWT, Algorithms: https://pyjwt.readthedocs.io/en/stable/algorithms.html
- PyJWT, API reference: https://pyjwt.readthedocs.io/en/stable/api.html
- PyJWT, Changelog: https://pyjwt.readthedocs.io/en/stable/changelog.html
- GitHub advisory GHSA-ffqj-6fqr-9h24 (PyJWT CVE-2022-29217): https://github.com/advisories/GHSA-ffqj-6fqr-9h24
- GitHub advisory GHSA-6c5p-j8vq-pqhj (python-jose CVE-2024-33663): https://github.com/advisories/GHSA-6c5p-j8vq-pqhj
- GitHub advisory GHSA-cjwg-qfpm-7377 (python-jose CVE-2024-33664): https://github.com/advisories/GHSA-cjwg-qfpm-7377
- python-jose releases: https://github.com/mpdavis/python-jose/releases
- pwdlib documentation: https://frankie567.github.io/pwdlib/
- pwdlib guide: https://frankie567.github.io/pwdlib/guide/
- pwdlib README: https://raw.githubusercontent.com/frankie567/pwdlib/main/README.md
- pwdlib changelog: https://raw.githubusercontent.com/frankie567/pwdlib/main/CHANGELOG.md
- argon2-cffi, "Choosing Parameters": https://argon2-cffi.readthedocs.io/en/stable/parameters.html
- argon2-cffi, API reference: https://argon2-cffi.readthedocs.io/en/stable/api.html
- passlib issue #148 (
cryptremoval): https://foss.heptapod.net/python-libs/passlib/-/issues/148 - passlib issue #187 (maintenance status): https://foss.heptapod.net/python-libs/passlib/-/issues/187
- pyca/bcrypt issue #684 (passlib and bcrypt 4.1): https://github.com/pyca/bcrypt/issues/684
- PyPI JSON, passlib: https://pypi.org/pypi/passlib/json
- PyPI JSON, libpass: https://pypi.org/pypi/libpass/json
- PyPI JSON, pwdlib: https://pypi.org/pypi/pwdlib/json
- PyPI JSON, PyJWT: https://pypi.org/pypi/PyJWT/json
- PyPI JSON, python-jose: https://pypi.org/pypi/python-jose/json
- PyPI JSON, pydantic-settings: https://pypi.org/pypi/pydantic-settings/json
- PEP 594, "Removing dead batteries from the standard library": https://peps.python.org/pep-0594/
- RFC 6749, The OAuth 2.0 Authorization Framework: https://www.rfc-editor.org/rfc/rfc6749.txt
- RFC 6750, Bearer Token Usage: https://www.rfc-editor.org/rfc/rfc6750.txt
- RFC 7519, JSON Web Token: https://www.rfc-editor.org/rfc/rfc7519.txt
- RFC 8037, CFRG ECDH and Signatures in JOSE: https://www.rfc-editor.org/rfc/rfc8037.txt
- RFC 8725, JSON Web Token Best Current Practices: https://www.rfc-editor.org/rfc/rfc8725.txt
- RFC 9106, Argon2: https://www.rfc-editor.org/rfc/rfc9106.txt
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110.txt
- RFC 9700, OAuth 2.0 Security Best Current Practice: https://www.rfc-editor.org/rfc/rfc9700.txt
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- OWASP Session Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
- OWASP Forgot Password Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html
- OWASP Password Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
- OWASP JSON Web Token Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_Cheat_Sheet.html
- OWASP CSRF Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
- OWASP API Security Top 10 2023, API2 Broken Authentication: https://owasp.org/API-Security/editions/2023/en/0xa2-broken-authentication/
- MDN, Set-Cookie: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie
- MDN, WWW-Authenticate: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/WWW-Authenticate
- Python,
secrets: https://docs.python.org/3/library/secrets.html - Python,
hmac: https://docs.python.org/3/library/hmac.html - Python,
hashlib: https://docs.python.org/3/library/hashlib.html - Starlette, Requests: https://starlette.dev/requests/
- Starlette, Responses (
set_cookie): https://starlette.dev/responses/ - Pydantic, Types (
SecretStr): https://docs.pydantic.dev/latest/api/types/ - Pydantic, Settings Management: https://docs.pydantic.dev/latest/concepts/pydantic_settings/
- Laravel 13, Sanctum: https://laravel.com/docs/13.x/sanctum
- Laravel 13, Passport: https://laravel.com/docs/13.x/passport
- Laravel 13, Fortify: https://laravel.com/docs/13.x/fortify
- Laravel 13, Hashing: https://laravel.com/docs/13.x/hashing
- Laravel 13, Resetting Passwords: https://laravel.com/docs/13.x/passwords
- golang-jwt/jwt v5 README: https://raw.githubusercontent.com/golang-jwt/jwt/main/README.md
- golang-jwt/jwt v5
parser_option.go: https://raw.githubusercontent.com/golang-jwt/jwt/main/parser_option.go - golang-jwt/jwt v5
validator.go: https://raw.githubusercontent.com/golang-jwt/jwt/main/validator.go - golang.org/x/crypto/bcrypt source: https://raw.githubusercontent.com/golang/crypto/master/bcrypt/bcrypt.go
- golang.org/x/crypto/argon2 source (
IDKey): https://raw.githubusercontent.com/golang/crypto/master/argon2/argon2.go - Go
encoding/base64source (RawURLEncoding): https://go.dev/src/encoding/base64/base64.go - Go
crypto/subtlesource (ConstantTimeCompare): https://go.dev/src/crypto/subtle/constant_time.go - pwdlib bcrypt hasher source (
rounds: int = 12,2[abxy]): https://raw.githubusercontent.com/frankie567/pwdlib/main/pwdlib/hashers/bcrypt.py