Sessions, Tokens or API Keys? Trade-offs and Pitfalls
Compare server-side sessions, signed JWTs and hashed API keys; set session cookies with the right attributes and timeouts, verify JWTs with a pinned algorithm and required claims, and rotate refresh tokens with reuse detection.
Contentsand lesson path
On this page
- Why it matters
- Three kinds of credential, and API key design
- Session cookies: attributes, timeouts and a new ID at login
- Verifying a JWT: pin the algorithm, require the claims
- Revoking tokens: short access tokens, rotating refresh tokens
- Check your understanding
- Apply it
- Review prompt
Lessons of Authentication & Authorization
- Identity, Credentials and Permission Models (RBAC, ABAC, ReBAC) Concept · 20 min
- Storing Passwords So a Breach Is Not a Disaster Worked example · 20 min
- Sessions, Tokens or API Keys? Trade-offs and Pitfalls Concept · 30 min
- Delegated Login with OAuth 2.0 and OpenID Connect, and Stopping Token Replay Concept · 30 min
- Lab: Roles and Ownership Checks in FastAPI Lab · 30 min
- Check: Spot the Authorization Bug Knowledge check · 10 questions
What you will learn
- Compare server-side sessions with signed tokens (JWT) and implement one correctly, including cookie flags, expiry, refresh rotation, revocation and signature and claim validation.
- Issue API keys for machine clients that are generated from a secure random source, shown once, stored only as a hash with a lookup prefix, limited by scopes, and rotated with an overlap window or revoked immediately.
Prerequisites: HTTP & APIs
01. Why it matters
After login, every request must prove who sent it, and the credential you choose decides what you can do later. Teams often pick JSON Web Tokens (JWTs) because they need no lookup, then find they cannot sign out a stolen device without adding server state back. Others use browser sessions for machine clients, where API keys fit better.
This lesson compares server-side sessions, signed tokens and API keys, then implements the details that make each one safe: cookie attributes and timeouts, JWT signature and claim checks, refresh token rotation and hashed, scoped keys.
02. Three kinds of credential, and API key design
- Server-side session: the server creates a random session ID, stores what it means (user, expiry) in its own store, and sends the ID in a cookie. Each request costs a lookup, but revoking is immediate: delete the record.
- Signed token (JWT): the server signs a set of claims (who, for which API, until when). Any service with the verification key can check it without a lookup, but a token stays valid until its
exptime, even after the user changes their password. - API key: a long-lived random secret for machine clients such as CI jobs or partner integrations, limited by scopes, stored only as a hash and shown once.
An HttpOnly cookie keeps the session ID away from JavaScript, so a cross-site scripting (XSS) bug cannot read and steal it. Injected script can still send requests as the user, because the browser attaches the cookie, so XSS must still be prevented, and cookie-authenticated endpoints need CSRF protection (SameSite plus an anti-CSRF token or an Origin check).
API keys need four design rules of their own:
- Random, with a prefix: generate the secret with
secrets.token_urlsafe(32)and put a prefix such assk_live_in front, so secret scanners can spot leaked keys. - Hashed storage: store only the SHA-256 hash plus a short, non-secret lookup prefix to find the row, and show the full key once. A fast hash is enough because the key is long and random.
- Scopes: attach specific permissions (
["webhooks:read", "invoices:write"]) instead of full account access. - Rotation with overlap: allow two active keys, let the client deploy key B while key A still works, record a last-used time per key, and revoke A once its traffic stops. A leaked key is revoked at once instead.
04. Verifying a JWT: pin the algorithm, require the claims
A JWT has three base64url parts, header.payload.signature. The header names the signing algorithm (alg); the payload carries claims from RFC 7519: iss (who issued it), sub (who it is about), aud (which API it is for), exp (when it expires), iat (when it was issued) and optionally jti (a unique ID, useful for revocation lists).
Two classic attacks abuse verifiers that trust the header. With alg: none the token has no signature at all. In algorithm confusion, an API expects an asymmetric algorithm such as RS256 or EdDSA, and the attacker signs a forged token with HS256 (HMAC) using the API's public key as the shared secret. A verifier that reads alg from the token computes the same HMAC and accepts it. RFC 8725 (JWT Best Current Practices) therefore says libraries must let the caller fix the accepted algorithms and must not use any others.
Here is a verifier with PyJWT 2.15.1. It runs in the virtual environment from the previous lesson after uv pip install "pyjwt[crypto]==2.15.1":
import jwt
ISSUER = "https://auth.example.com"
AUDIENCE = "https://api.example.com"
def verify_access_token(token: str, public_key) -> dict:
"""Return the claims of a valid token; raise jwt.InvalidTokenError otherwise."""
return jwt.decode(
token,
key=public_key,
algorithms=["EdDSA"], # pinned by the server, never taken from the token
audience=AUDIENCE, # reject tokens minted for another API
issuer=ISSUER, # reject tokens from another issuer
leeway=30, # allow 30 seconds of clock skew, no more
options={"require": ["exp", "iat", "iss", "aud", "sub"]},
)
algorithms comes from your configuration, never from the token. audience and issuer reject tokens minted for another API or by another issuer. leeway=30 accepts a token up to 30 seconds past exp, which absorbs small clock differences between servers; keep it to seconds. require matters because PyJWT checks exp only when the token has one: without it, a token with no exp claim never expires. (Once you pass audience and issuer, PyJWT already refuses a token that lacks aud or iss.) The tests sign real tokens with an Ed25519 key and attack the verifier:
import base64
import hashlib
import hmac
import json
import time
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from verify_jwt import AUDIENCE, ISSUER, verify_access_token
PRIVATE = Ed25519PrivateKey.generate()
PUBLIC = PRIVATE.public_key()
def make(signing_key=PRIVATE, **changes):
now = int(time.time())
claims = {"iss": ISSUER, "aud": AUDIENCE, "sub": "usr_48102",
"iat": now, "exp": now + 600}
claims.update(changes)
claims = {k: v for k, v in claims.items() if v is not None} # None = drop it
return jwt.encode(claims, signing_key, algorithm="EdDSA")
def b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def forge_hs256(secret: bytes) -> str:
"""Attacker: sign with HMAC, using the server's public key as the secret."""
now = int(time.time())
head = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
body = b64(json.dumps({"iss": ISSUER, "aud": AUDIENCE, "sub": "usr_admin",
"iat": now, "exp": now + 600}).encode())
sig = hmac.new(secret, f"{head}.{body}".encode(), hashlib.sha256).digest()
return f"{head}.{body}.{b64(sig)}"
def test_valid_token_returns_claims():
assert verify_access_token(make(), PUBLIC)["sub"] == "usr_48102"
def test_ten_seconds_past_exp_is_inside_the_leeway():
assert verify_access_token(make(exp=int(time.time()) - 10), PUBLIC)PUBLIC_PEM = PUBLIC.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
@pytest.mark.parametrize("token, error", [
(make(aud="https://billing.example.com"), jwt.InvalidAudienceError),
(make(iss="https://evil.example.net"), jwt.InvalidIssuerError),
(make(exp=int(time.time()) - 60), jwt.ExpiredSignatureError),
(make(sub=None), jwt.MissingRequiredClaimError),
(make(aud=None), jwt.MissingRequiredClaimError),
(make(exp=None), jwt.MissingRequiredClaimError),
(make(signing_key=Ed25519PrivateKey.generate()), jwt.InvalidSignatureError),
(jwt.encode({"sub": "usr_admin"}, None, algorithm="none"),
jwt.InvalidAlgorithmError),
(forge_hs256(PUBLIC_PEM), jwt.InvalidAlgorithmError),
], ids=["wrong-aud", "wrong-iss", "expired", "no-sub", "no-aud", "no-exp",
"other-key", "alg-none", "alg-confusion"])
def test_bad_tokens_are_rejected(token, error):
with pytest.raises(error):
verify_access_token(token, PUBLIC)python -m pytest -v --no-header -p no:cacheprovider test_verify_jwt.py============================= test session starts ==============================
collecting ... collected 11 items
test_verify_jwt.py::test_valid_token_returns_claims PASSED [ 9%]
test_verify_jwt.py::test_ten_seconds_past_exp_is_inside_the_leeway PASSED [ 18%]
test_verify_jwt.py::test_bad_tokens_are_rejected[wrong-aud] PASSED [ 27%]
test_verify_jwt.py::test_bad_tokens_are_rejected[wrong-iss] PASSED [ 36%]
test_verify_jwt.py::test_bad_tokens_are_rejected[expired] PASSED [ 45%]
test_verify_jwt.py::test_bad_tokens_are_rejected[no-sub] PASSED [ 54%]
test_verify_jwt.py::test_bad_tokens_are_rejected[no-aud] PASSED [ 63%]
test_verify_jwt.py::test_bad_tokens_are_rejected[no-exp] PASSED [ 72%]
test_verify_jwt.py::test_bad_tokens_are_rejected[other-key] PASSED [ 81%]
test_verify_jwt.py::test_bad_tokens_are_rejected[alg-none] PASSED [ 90%]
test_verify_jwt.py::test_bad_tokens_are_rejected[alg-confusion] PASSED [100%]
============================== 11 passed in 0.44s ==============================The no-exp case is refused only because exp is in require; no-aud would be refused even without require, because audience is set. Both header attacks fail with InvalidAlgorithmError because neither none nor HS256 is in the allowed list. PyJWT also refuses to use a PEM public key as an HMAC secret, but treat that as a second layer, not a reason to skip the allowlist.
05. Revoking tokens: short access tokens, rotating refresh tokens
A signed token cannot be recalled, so keep its life short and put the revocable state somewhere else:
- Access token: lives 5 to 15 minutes and is sent as
Authorization: Bearer <token>. APIs verify it without a lookup. - Refresh token: a random value that lives days, kept in an
HttpOnly,Secure,SameSite=Strictcookie or the mobile keystore, and backed by a database row the server can revoke. - Rotation with reuse detection: each refresh revokes the old refresh token and issues a new one. If an already-rotated token comes back, someone copied it, so the server revokes that whole family: every token descended from the same sign-in. The user's other devices keep their own families.
import hashlib
import secrets
import time
from sqlalchemy import Connection, Engine, insert, select, update
from app_tables import refresh_tokens as rt # token_hash, user_id, family_id,
# expires_at, family_expires_at, revoked_at (times in Unix seconds)
REFRESH_TTL = 14 * 86400 # sliding lifetime of one refresh token
LOGIN_TTL = 30 * 86400 # absolute lifetime of the whole login (family)
def sha256(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
def issue_family(conn: Connection, user_id: int) -> str:
"""Start a login: the first refresh token of a new family."""
raw, now = secrets.token_urlsafe(32), int(time.time())
conn.execute(insert(rt).values(
token_hash=sha256(raw), user_id=user_id, family_id=secrets.token_hex(16),
expires_at=now + REFRESH_TTL, family_expires_at=now + LOGIN_TTL))
return raw
def rotate_refresh_token(engine: Engine, raw_token: str) -> tuple[str, str]:
now, h = int(time.time()), sha256(raw_token)
reused = False
with engine.begin() as conn: # commits on exit, also on the reuse path
# Claim the token in one atomic statement: of two concurrent callers
# with the same token, exactly one gets a row back
row = conn.execute(
update(rt)
.where(rt.c.token_hash == h, rt.c.revoked_at.is_(None),
rt.c.expires_at > now, rt.c.family_expires_at > now)
.values(revoked_at=now)
.returning(rt.c.user_id, rt.c.family_id, rt.c.family_expires_at)
).first()
if row is None:
old = conn.execute(select(rt.c.family_id, rt.c.revoked_at)
.where(rt.c.token_hash == h)).first()
reused = old is not None and old.revoked_at is not None
if reused: # a rotated token came back: revoke this login only
conn.execute(update(rt)
.where(rt.c.family_id == old.family_id,
rt.c.revoked_at.is_(None))
.values(revoked_at=now))
else:
new_raw = secrets.token_urlsafe(32)
conn.execute(insert(rt).values(
token_hash=sha256(new_raw), user_id=row.user_id,
family_id=row.family_id, family_expires_at=row.family_expires_at,
# Never extend past the login's absolute expiry
expires_at=min(now + REFRESH_TTL, row.family_expires_at)))
if reused:
raise SecurityBreachError("Refresh token reused; login revoked")
if row is None:
raise UnauthorizedError("Invalid or expired refresh token")
return create_access_jwt(row.user_id, minutes=10), new_raw- Claim the token atomically. A read-then-save lets two concurrent refreshes with the same token both see it as valid and both mint new tokens. The single
UPDATE ... WHERE revoked_at IS NULL ... RETURNINGlets exactly one caller win. - Revoke the family, and commit it. Reuse revokes only that login. The revocation commits before the exception is raised; raising inside the transaction would roll it back.
- Cap the lifetime. Each rotation sets a fresh 14-day expiry, but never past
family_expires_at, so a stolen chain cannot be extended forever.
Strict reuse detection has a cost: a client that retries a refresh after a timeout, or two tabs refreshing at once, looks like an attacker, and that device is signed out. If your clients do this, allow a short grace window: when a token rotated in the last few seconds comes back, issue another token in the same family instead of revoking the family. The table stores only hashes, so the server cannot send the first successor again. RFC 9700 (OAuth 2.0 Security Best Current Practice) requires public clients to use refresh token rotation or sender-constrained refresh tokens.
06. Check your understanding
07. Apply it
In your practice API, choose sessions or tokens. For sessions, store created_at and last_seen_at, enforce an idle and an absolute timeout, and test that a session past either limit gets 401. For tokens, use the verifier from this lesson with 10-minute access tokens, add the rotating refresh table, and port the negative tests. For the reporting client, issue a hashed, scoped API key and rotate it with an overlap window.
The next lesson moves the token issuer out of your app: OAuth 2.0 and OpenID Connect, and how an API validates tokens from an identity provider.
08. Review prompt
Without looking back, name each attribute of a safe session cookie and the attack it limits, and explain why the server still needs idle and absolute timeouts. List the arguments a JWT verifier needs and what goes wrong without each one. Finally, explain how refresh token rotation detects a stolen token.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.