Lesson 14 of 59Building a real API
Authentication and JWTs
Hash passwords safely, issue and verify signed tokens without algorithm pitfalls, and protect FastAPI routes with OAuth2 bearer auth.
Auth is the part of a backend where small mistakes become headlines: plaintext passwords in a leaked database, tokens that never expire, an API that lets user 7 read user 8's notes. It is also asked about in nearly every backend interview. In this lesson you build the pieces from scratch with the standard library, so the FastAPI version is no longer magic.
Authentication vs authorization
Two different questions, often mixed up:
- Authentication (authn): who are you? Proving identity with a password, a token, a passkey.
- Authorization (authz): what are you allowed to do? Can this user delete this todo? Is this user an admin?
They map to two status codes. 401 Unauthorized means "I do not know who you are" (despite the name, it is about authentication). 403 Forbidden means "I know who you are, and the answer is no".
Match each situation to the right response.
Storing passwords: hash, salt, slow
Never store a password. Store a hash: the output of a one-way function. At login you hash what the user typed and compare. If the database leaks, attackers get hashes, not passwords.
Two more ingredients make this safe:
- A salt: random bytes, different for every user, mixed into the hash and stored next to it. Without it, everyone with the password
hunter2has the same hash, and attackers use precomputed tables to reverse common passwords instantly. - A slow hash. SHA-256 is designed to be fast (billions per second on a GPU), which is great for attackers. Password hashes like Argon2id, bcrypt, scrypt or PBKDF2 with many iterations are deliberately slow and tunable.
Press Run (⌘ Enter) to see what happens.The two hashes differ because each has its own salt, yet both verify. The stored string carries the algorithm, iteration count and salt, so you can raise the iterations later and rehash users when they next log in. hmac.compare_digest compares in constant time, so an attacker cannot learn how many leading characters matched by timing the response.
In a real FastAPI app, use a maintained library rather than your own code. The FastAPI docs use pwdlib with Argon2:
from pwdlib import PasswordHash
password_hash = PasswordHash.recommended() # Argon2id with sensible settings
hashed = password_hash.hash("correct horse battery staple")
password_hash.verify("correct horse battery staple", hashed) # TrueSessions or tokens?
After login, the server needs to recognise you on the next request without asking for your password again. There are two main approaches.
| Server sessions | Signed tokens (JWT) | |
|---|---|---|
| What the client holds | A random session id in a cookie | A token containing the claims and a signature |
| What the server stores | A row per session (database or Redis) | Nothing per user, just the secret key |
| Logout or revoke | Delete the row: instant | Hard until it expires (needs a deny list) |
| Scaling | Every request looks up the session | Any server with the key can verify alone |
| Typical use | Classic web apps | APIs, mobile apps, service to service |
Both are fine. Sessions are simpler to revoke; tokens avoid a lookup per request. Most token setups mix in a little state anyway, as you will see with refresh tokens.
Inside a JWT
A JSON Web Token is three base64url-encoded parts joined by dots: header.payload.signature.
- Header:
{"alg": "HS256", "typ": "JWT"}, which algorithm signed it. - Payload: the claims, such as
sub(subject: the user id),iat(issued at) andexp(expiry), as Unix timestamps. - Signature:
HMAC-SHA256(secret, header + "." + payload). Only someone with the secret can make a valid one.
Base64url is a way to write bytes as URL-safe text (- and _ instead of + and /, with the = padding removed). It is an encoding, not encryption. Anyone can read a JWT's payload. The signature only proves it was not changed.
Press Run (⌘ Enter) to see what happens.The forged token fails because changing the payload changes what the signature should be, and the attacker cannot recompute it without the secret.
Using the code above, what does this print?
print(len(token.split(".")), unb64url(b64url(b"hi")))Auth in FastAPI: the OAuth2 password flow
FastAPI ships helpers for the OAuth2 password flow: the client posts a username and password as a form to a token endpoint and gets back a bearer token to send as Authorization: Bearer <token> on later requests. Here it is with the PyJWT library (uv add pyjwt pwdlib[argon2]).
from datetime import UTC, datetime, timedelta
from typing import Annotated
import jwt
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from app.core.config import settings
from app.core.security import password_hash
router = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
@router.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()], db: DB):
user = get_user_by_email(db, form.username)
if user is None or not password_hash.verify(form.password, user.hashed_password):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Incorrect email or password")
expires = datetime.now(UTC) + timedelta(minutes=15)
token = jwt.encode({"sub": str(user.id), "exp": expires}, settings.secret_key, algorithm="HS256")
return {"access_token": token, "token_type": "bearer"}
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], db: DB) -> User:
unauthorized = HTTPException(
status.HTTP_401_UNAUTHORIZED, "Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
claims = jwt.decode(token, settings.secret_key, algorithms=["HS256"])
except jwt.InvalidTokenError: # bad signature, expired, malformed
raise unauthorized
user = db.get(User, int(claims["sub"]))
if user is None:
raise unauthorized
return user
CurrentUser = Annotated[User, Depends(get_current_user)]OAuth2PasswordBearer is a dependency that reads the Authorization: Bearer ... header (and answers 401 if it is missing). It also adds an Authorize button to /docs. algorithms=["HS256"] pins the algorithm, which blocks the classic attack of sending a token with "alg": "none". Note the login error does not say whether the email or the password was wrong, so attackers cannot use it to discover which emails have accounts.
Protecting a route is now one parameter, and authorization is a check on ownership:
@router.get("/todos/{todo_id}")
def get_todo(todo_id: int, user: CurrentUser, db: DB) -> TodoRead:
todo = db.get(Todo, todo_id)
if todo is None or todo.user_id != user.id:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Todo not found")
return todoThe password travels once, over HTTPS, as form data.
Order what the server does during POST /token.
- Tap the steps below in the right order.
Access tokens, refresh tokens and where to keep them
A JWT cannot easily be revoked, so keep access tokens short-lived: 5 to 15 minutes. To avoid logging in every 15 minutes, also issue a refresh token: long-lived (days or weeks), used only at a /refresh endpoint to get a new access token. Store refresh tokens (or their hash) in the database, so logout or a stolen-device report can revoke them, and rotate them: each use returns a new refresh token and invalidates the old one.
Where the browser keeps tokens matters:
localStorageis readable by any JavaScript on the page. One XSS bug (an attacker's script running on your site) steals every token.- An
httpOnlycookie cannot be read by JavaScript at all. AddSecure(HTTPS only) andSameSite=LaxorStrict(limits cross-site sending, which defends against CSRF).
response.set_cookie(
"refresh_token", refresh_token,
httponly=True, secure=True, samesite="strict",
max_age=60 * 60 * 24 * 14, path="/refresh",
)Mobile apps and server-to-server clients send bearer tokens in the header and keep them in the platform's secure storage instead.
localStorage. What is the main risk?Algorithm pitfalls
The header of a JWT says which algorithm signed it. The single most important rule in this section: the token does not get to choose how it is verified. Your server does. Most famous JWT vulnerabilities come from libraries or code that read alg from the token and obeyed it.
alg: none. The JWT standard defines an "unsecured" token with "alg": "none" and an empty signature. A verifier that trusts the header accepts it, so an attacker writes any claims they like, sets alg to none, and drops the signature.
HS/RS confusion. With RS256 the server signs with a private key and verifies with a public key, which is public by design (often published at a JWKS URL). HS256 uses one shared secret for both. Now imagine a verifier written as "decode with key, using whatever algorithm the header says", where key is the RSA public key. An attacker builds a token with "alg": "HS256" and signs it with HMAC, using the public key's bytes as the HMAC secret. The verifier runs HMAC with the same bytes, the signatures match, and the forged token is accepted.
Run both attacks against a naive verifier and a strict one:
Press Run (⌘ Enter) to see what happens.Both forged tokens fool the naive verifier, and the strict one rejects both before looking at the signature, because it has a fixed allow list. In PyJWT this is the algorithms argument, and the library makes it hard to get wrong. Tested with PyJWT 2.15:
jwt.decode(token, key)with noalgorithmsraisesDecodeError: it is required.- An
alg: nonetoken decoded withalgorithms=["RS256"]raisesInvalidAlgorithmError. - Trying to use a PEM public key as an HMAC secret raises
InvalidKeyError, which closes the confusion attack at the library level.
Still, write the code so it would be safe with a weaker library:
claims = jwt.decode(
token,
public_key,
algorithms=["RS256"], # exactly one family; never mix HS256 and RS256 in one list
audience="https://api.example.com",
issuer="https://auth.example.com/",
options={"require": ["exp", "iat", "sub"]},
)Three more habits seniors have:
- Never mix symmetric and asymmetric algorithms in one
algorithmslist.["RS256", "HS256"]reopens the confusion attack for any library that does not check key types. If you are migrating between algorithms, use separate keys and separate decode paths. - Check
audandisswhen tokens come from a shared issuer. If your company's identity provider signs tokens for ten services, a token meant for the reporting service is validly signed for yours too. The audience claim is what says "this token is for me". PyJWT raisesInvalidAudienceErrorif a token carries anaudand you do not passaudience=, which surprises people the first time. - Handle
kidas a lookup key, never as a path or query. Thekid(key id) header says which of the issuer's keys signed the token, so keys can rotate: the issuer publishes old and new keys side by side in its JWKS, and you pick the one whosekidmatches. Read it withjwt.get_unverified_header(token)and look it up in the issuer's published key set.PyJWKClient(jwks_url).get_signing_key_from_jwt(token)does this with caching. Akidis attacker-controlled input until the signature checks out, so akidof../../dev/nullor' OR 1=1 --must never reach a file path or SQL query. An unknownkidshould trigger at most one rate-limited refresh of the key set, then a401.
If you only issue tokens for your own API, HS256 with a long random secret from your settings is fine. Asymmetric keys earn their extra complexity when other services must verify tokens without being able to mint them, which is the situation in Log In with Google: OAuth 2 and OpenID Connect.
jwt.decode(token, public_key, algorithms=['RS256', 'HS256']). What is wrong?Using the code above, what does this print?
h, c, _ = make({"alg": "RS256"}, admin)
fake = f"{h}.{c}.not-a-real-signature"
print(naive_decode(fake, PUBLIC_KEY), strict_decode(fake, PUBLIC_KEY, ["RS256"]))Where next
This lesson built password login and bearer tokens for your own API. Three lessons pick up where it stops. Cookie Sessions, CSRF and Logout That Works covers the other column of the sessions or tokens table: server-side sessions, cookie attributes, CSRF and logout that really ends a session. Log In with Google: OAuth 2 and OpenID Connect replaces your password form with an external identity provider, using the authorization code flow with PKCE and validating tokens against the provider's published keys, which is where kid and RS256 matter. And once you know who the user is, Authorization: Roles, Permissions and Ownership covers what they may do, beyond the ownership check in this lesson.
Practice
Salted password hashing
Write the two functions every login system needs, using only the standard library.
hash_password(password, salt=None, iterations=100_000) -> str
- If
saltisNone, generate 16 random bytes withos.urandom(16). - Derive the hash with
hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations). - Return one string holding everything needed to verify later:
pbkdf2_sha256$<iterations>$<salt as hex>$<hash as hex>verify_password(password, stored) -> bool
- Parse
stored, recompute the hash with its salt and iteration count, and compare withhmac.compare_digest(constant time). - Return
False(never raise) ifstoredis malformed: wrong number of parts, wrong algorithm name, or bad hex/number.
Sign and verify a JWT
Implement HS256 JSON Web Tokens with the standard library. The base64url helpers are given.
create_token(payload, secret, now, ttl=900) -> str
- Header:
{"alg": "HS256", "typ": "JWT"}. - Claims: a copy of
payloadplus"iat": nowand"exp": now + ttl. - Encode header and claims as JSON (
json.dumps), then base64url, givinghandp. - Signature:
HMAC-SHA256(secret, f"{h}.{p}"), base64url-encoded. - Return
f"{h}.{p}.{signature}".
verify_token(token, secret, now) -> dict | None
Return the claims dict if the token is valid, otherwise None (never raise). Invalid means any of:
- not exactly three parts, or parts that are not valid base64url JSON;
- header
algis not"HS256"(this blocks the"alg": "none"attack); - the signature does not match (compare with
hmac.compare_digest); - expired:
now >= exp, or noexpclaim.
now is passed in (Unix seconds) so tests do not depend on the clock.
- authentication vs authorization
- Authn: who are you (401 when it fails). Authz: what may you do (403, or 404 to hide a resource).
- salt
- Random bytes stored with each password hash so identical passwords hash differently.
- JWT
header.payload.signature, base64url-encoded. Readable by anyone, tamper-proof without the secret.- bearer token
- A token sent as
Authorization: Bearer <token>. Whoever holds it is treated as the user. - refresh token
- A long-lived, revocable token used only to get new short-lived access tokens.
- httpOnly cookie
- A cookie JavaScript cannot read, so XSS cannot steal the token inside it.
- algorithm confusion
- Forging a token by making the verifier use HMAC with a public key as the secret. Prevented by a fixed
algorithmsallow list. - kid
- A JWT header naming which of the issuer's keys signed the token, so keys can rotate. Untrusted input until verified.