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

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

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 exp time, 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 as sk_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.

03. Session cookies: attributes, timeouts and a new ID at login

The login endpoint in the password storage lesson calls response.set_cookie("session", sid, max_age=8 * 3600, httponly=True, secure=True, samesite="lax"). Its test reads back this Set-Cookie header (value removed):

Expected output · Set-Cookie attributes after login
session=<random ID>; HttpOnly; Max-Age=28800; Path=/; SameSite=lax; Secure
  • Secure: the browser sends the cookie only over HTTPS, never over plain HTTP, where anyone on the network path could read it.
  • HttpOnly: page scripts cannot read it.
  • SameSite=Lax: the browser leaves it off most cross-site requests, such as a form another site posts to yours; it is still sent when the user follows a link to you. Strict also drops it on those links, which OWASP prefers when your app can live with it.
  • Max-Age=28800: the browser deletes it after 8 hours. Without Max-Age or Expires, it lasts until the browser session ends, which many browsers restore after a restart.
  • No Domain: only the exact host that set it receives it, not every subdomain.

The browser's expiry is a convenience, not a control, because a stolen cookie can be replayed by any client. Enforce two timeouts on the server: an idle timeout (OWASP gives 2 to 5 minutes for high-value apps and 15 to 30 minutes for low-risk ones) and an absolute timeout that ends the session however active it is, for example 4 to 8 hours for a working day. Store created_at and last_seen_at with each session and reject it when either limit is passed.

Issue a fresh session ID whenever privilege changes, above all at login, and delete the old one. Otherwise an attacker who planted a known ID in the victim's browser (session fixation) is signed in as soon as the victim is. Logout and password reset delete the record on the server, which is the revocation that sessions make easy.

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":

Python · verify_jwt.py
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:

Python · test_verify_jwt.py (1 of 2)
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)
Python · test_verify_jwt.py (2 of 2)
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)
Shell · run the tests
python -m pytest -v --no-header -p no:cacheprovider test_verify_jwt.py
Illustrative output (run time varies)
============================= 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=Strict cookie 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.
Python · auth/refresh.py (excerpt: rotation with reuse detection, SQLAlchemy Core)
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 ... RETURNING lets 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

Practice check · 3 questions

Authentication credentials and security trade-offs

Three questions on session cookies, refresh rotation and JWT validation.

Q1. The login sets `Max-Age=28800`, but the session store keeps only the ID and the user, with no timestamps. Ana signs in at 09:00, and at 09:30 malware copies her cookie value. When does the copy stop working?
Q2. Two browser tabs refresh at the same moment with the same refresh token. With the strict rotation in this lesson, what happens?
Q3. A token has `sub`, `aud` and `iss` but no `exp`. What does `jwt.decode(token, key, algorithms=["EdDSA"], audience=AUD, issuer=ISS)` do, with no `options`?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

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