4. Authentication, Security & Configuration
Password Hashing & Bearer Token / JWT Authentication
Store user passwords safely with salted key stretching (pbkdf2_hmac / bcrypt), prevent timing attacks with hmac.compare_digest, and issue signed stateless Bearer tokens.
- Hash and verify passwords safely using per-user random salts and slow key-derivation
- Compare cryptographic signatures safely using constant-time hmac.compare_digest()
- Understand how signed Bearer / JWT tokens (header.payload.signature + exp) authenticate requests
Two security rules separate safe backends from headline-making data breaches:
- Never store plain-text passwords (and never use plain
sha256(password)—modern GPUs compute billions of unsalted SHA-256 hashes per second!). - Sign auth tokens cryptographically with an expiration timestamp (
exp) so users can't forge"sub": "1"or"role": "admin".
1. Architecture: Login Flow vs Authenticated Request Flow
Authentication spans two separate API flows:
Flow A — Login (`POST /auth/login`):
Email + Password ─▶ Fetch stored `salt$hash` ─▶ pbkdf2_hmac / argon2 verify ─▶ Return signed JWT
Flow B — Protected Route (`DELETE /tasks/42`):
Authorization: Bearer <jwt>
│
▼
Auth Guard (`Depends(get_current_user)`)
├─ Missing/bad signature/expired? ──▶ 401 Unauthorized
└─ Valid signature & exp! ──▶ Check ownership/role (403 Forbidden if unauthorized) ─▶ Handler2. Salted Slow Password Hashing (pbkdf2_hmac / argon2 vs sha256)
Why is plain hashlib.sha256(password) broken for passwords?
| Algorithm | Salted? | Work Factor / Memory Cost | Verdict for Passwords |
|---|---|---|---|
Plain MD5 / SHA-256 | No | Microseconds (built for speed!) | Unsafe — rainbow tables & GPU cracking |
hashlib.pbkdf2_hmac | Yes | 200,000+ iterations (stdlib) | Safe — great zero-dependency baseline |
bcrypt / argon2 (pwdlib) | Yes | High CPU + memory-hard (argon2id) | Best — gold standard against GPU/ASIC clusters |
Safe password hashing always combines two defenses:
- A unique random salt per user (
secrets.token_hex(16)) so two users with the same password produce completely different hashes. - Key stretching (hundreds of thousands of iterations) so brute-forcing every guess is intentionally expensive.
import hashlib
import hmac
import secrets
def hash_password(password: str) -> str:
salt = secrets.token_hex(16)
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode("utf-8"), 200_000)
return f"{salt}${dk.hex()}"
def verify_password(password: str, stored_hash: str) -> bool:
salt, expected_hex = stored_hash.split("$", maxsplit=1)
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode("utf-8"), 200_000)
return hmac.compare_digest(dk.hex(), expected_hex) # Constant-time compare!Standard == stops comparing at the first mismatched character, leaking tiny microsecond timing clues to attackers. hmac.compare_digest() always takes the same time regardless of where two digests differ.
3. JWT Structure (header.payload.signature) & Why Payloads Are NOT Encrypted
After POST /auth/login verifies the user's password, the backend issues a JSON Web Token (JWT) made of three Base64URL segments joined by dots:
1. HEADER
{"alg": "HS256", "typ": "JWT"}
Base64URL encoded
2. PAYLOAD
{"sub": "42", "exp": 1796030000}
Readable — NO secrets here!
3. SIGNATURE
HMAC_SHA256(h + "." + p, SECRET)
Stops tampering via compare_digest
Header and Payload are Base64URL-encoded (readable by anyone!), while Signature proves the server signed them with JWT_SECRET.
- Header: Declares token type and signing algorithm (
{"alg": "HS256", "typ": "JWT"}). - Payload (Claims): JSON metadata such as subject (
"sub": "42"), role, and expiration timestamp ("exp"). - Signature:
HMAC_SHA256(secret, header + "." + payload)(forHS256) or an asymmetric RSA/EdDSA signature (RS256/EdDSAwhen separate services verify tokens with a public key).
On subsequent requests, the client sends Authorization: Bearer <token>.
- Anyone holding a JWT can Base64URL-decode its middle payload segment in two lines of Python—so never put passwords, API keys, or private PII inside a JWT payload! Signing guarantees integrity (tamper-evidence), not secrecy.
- Always pin allowed algorithms when decoding (
jwt.decode(token, SECRET, algorithms=["HS256"])) so attackers cannot exploit"alg": "none"downgrade bugs.
401 Unauthorized vs 403 Forbidden & Token Revocation
- Return
401 Unauthorizedwhen theAuthorizationheader is missing, malformed, tampered with, or expired (exppassed). - Return
403 Forbiddenwhen the token is completely valid, but the authenticated user lacks permission (e.g.,"role": "student"accessing an admin endpoint). - Because stateless JWTs stay valid until
exp, keep access token lifetimes short (e.g.15–60 minutes) and pair them with revocable database/Redis refresh tokens if you need instant logout across devices.
Try It Yourself in the Playground
Run real cryptographic password hashing + salted verification + HMAC-signed Bearer tokens using Python's standard library (hashlib, hmac, secrets, base64):
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why do two calls to hash_password("same_password") produce different output strings?
Quick Checkpoints
Why should you NEVER store sensitive secrets (like credit card numbers or passwords) inside a standard JWT payload?
Why is hashlib.pbkdf2_hmac (or bcrypt/argon2) preferred over hashlib.sha256(password) for storing passwords?