Notes
All notes

Authentication Methods (API Design #5)

A contractor’s laptop is stolen. Inside: a CSV of API passwords for your staging environment, which — oops — shares credentials with production. By morning someone has listed every customer you have. The incident review asks one question that should have been asked at design time: why could a single secret, presented once, act as a person forever?

Authentication is the API answering “who are you?” This chapter walks the five answers you’ll meet in production — Basic auth, session-based auth, token-based auth, JWT, and the OAuth 2.0 / OIDC pair that dominates delegated access — with enough mechanism to implement each and enough scar tissue to know when not to.

By the end you will be able to decode a JWT by hand, diagram the authorization-code flow from memory, and explain why “we just use API keys for user auth” is usually a category error (keys get their own Chapter 7).

Authentication vs authorization

Keep the two words separate from the start:

Authentication always runs first, and its output should be a verified identity object your handlers can trust — never a re-parsed header, never a re-verified token deep in business logic. One middleware authenticates; everything downstream consumes.

Basic auth: the floor

Basic auth sends credentials on every request, base64-encoded (not encrypted — encoding is not secrecy):

GET /invoices HTTP/1.1
Authorization: Basic dXNlcjpwYXNzd29yZA==        # "user:password", base64

It is stateless and universally supported, which makes it fine for internal tooling and webhooks over TLS — and unacceptable for anything user-facing. The password crosses the wire on every request (maximizing exposure), there is no expiry or revocation short of changing the password, and browsers cache it aggressively. If a bearer of this header exists, the password does too. Treat it as a lock on a screen door.

Session-based auth: state on the server

The browser-era answer: POST /login with username and password once; the server creates a session record and returns an opaque id in a cookie:

Set-Cookie: session=9f3c2a…; HttpOnly; Secure; SameSite=Lax

Every later request carries the cookie; the server looks up the id in a session store (Redis, Postgres) and knows who you are. The properties follow from the lookup:

For a server-rendered web app with one API, sessions remain a solid default. The trouble starts when one API serves browsers, phones, CLIs, and partner servers at once.

Token-based auth and the JWT

Token auth inverts the session: instead of an opaque id that requires a lookup, the server issues a self-contained token that carries the identity, cryptographically signed so it can’t be forged. The dominant format is the JWT (JSON Web Token): three base64url segments joined by dots.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9   .   eyJzdWIiOiI3NyIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc1OTQwMDAwMH0   .   SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
       header (algorithm + type)                     payload (claims)                                      signature

The payload holds claims — sub (subject), iss (issuer), exp (expiry), iat (issued-at), plus your own (role, tenant). The signature is computed over header.payload with a secret (HMAC) or a private key (RSA/ECDSA), so any tampering invalidates it. Verification is local — no store lookup:

import hmac, hashlib, base64, json, time

def b64url_decode(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def verify_jwt(token: str, secret: bytes) -> dict:
    header_b64, payload_b64, sig_b64 = token.split(".")
    expected = hmac.new(secret, f"{header_b64}.{payload_b64}".encode(),
                        hashlib.sha256).digest()
    if not hmac.compare_digest(expected, b64url_decode(sig_b64)):
        raise ValueError("bad signature")
    claims = json.loads(b64url_decode(payload_b64))
    if claims.get("exp", 0) < time.time():
        raise ValueError("token expired")
    return claims        # {"sub": "77", "role": "admin", ...}

Two properties define JWTs in practice. Statelessness: any server with the key verifies any token in microseconds — beautiful for horizontally scaled fleets. Un-revocability: a valid signature is valid until exp, so a stolen token works until it dies. The mitigation is short-lived access tokens (5–15 minutes) paired with long-lived refresh tokens (revocable, stored server-side) that mint new access tokens. You trade “logout works instantly” for “logout works within one access-token lifetime” — usually the right trade at scale, and a terrible one if you set exp to 30 days.

One rule that cannot be repeated enough: the payload is signed, not encrypted. Anyone can base64-decode it. Never put secrets, passwords, or PII you wouldn’t print on a billboard into JWT claims.

The refresh-token pattern, as a picture:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.4cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (c) at (0,0) {client};
  \node[b, fill=orange!16] (a) at (4.6,0.9) {auth server};
  \node[b, fill=gray!12] (r) at (4.6,-0.9) {resource API};
  \draw[a] (c) to[bend left=12] node[above, font=\rmfamily\scriptsize] {refresh token (long-lived, revocable)} (a);
  \draw[a, dashed] (a) to[bend left=12] node[below, font=\rmfamily\scriptsize] {new access token (15 min)} (c);
  \draw[a] (c) to[bend right=12] node[below, font=\rmfamily\scriptsize] {access token on every call} (r);
\end{tikzpicture}

Quantify why the lifetimes matter. If a token leaks at a random moment, its expected remaining life is half its validity window, so the attacker’s expected abuse window is

\[ E[\Delta t] = \frac{T_{\text{token}}}{2} \]

— five hours for a 10 h token, seven minutes for a 15 min token. Lifetime is the revocation granularity for stateless tokens, which is why “short access + revocable refresh” is the standard split and why a 30-day access token is a standing invitation.

OAuth 2.0: delegated access

OAuth 2.0 answers a different question: “how does a third-party app act on a user’s behalf without ever seeing the user’s password?” It defines four roles — resource owner (the user), client (the third-party app), authorization server (issues tokens), resource server (your API) — and the canonical dance is the authorization code flow:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.5cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (u) at (0,0) {user};
  \node[b, fill=green!10] (c) at (3.6,0) {client app};
  \node[b, fill=orange!16] (a) at (7.2,0) {auth server};
  \node[b, fill=gray!12] (r) at (10.8,0) {your API};
  \draw[a] (u.south) ++(0.6,0) -- ++(0,-0.7) -| node[pos=0.25, below, font=\rmfamily\scriptsize] {1. login + consent} (a.south);
  \draw[a, dashed] (a.south) ++(-0.6,0) -- ++(0,-1.15) -| node[pos=0.25, below, font=\rmfamily\scriptsize] {2. authorization code} (c.south);
  \draw[a] (c.south) ++(0.6,0) -- ++(0,-1.6) -| node[pos=0.3, below, font=\rmfamily\scriptsize] {3. code + secret $\rightarrow$ tokens} (a.south);
  \draw[a] (c.north) to[bend left=20] node[above, font=\rmfamily\scriptsize] {4. API call + access token} (r.north);
\end{tikzpicture}

The code travels through the browser (untrusted); the exchange for tokens happens server-to-server with the client’s secret (trusted). The user authenticates to the authorization server — the third-party app never sees a password, and it receives a token limited to the scopes the user approved (read:invoices, never “everything”). Public clients (mobile apps, SPAs) can’t hold a secret, so they add PKCE: a one-time code challenge that binds the token exchange to the device that started the flow.

Other flows exist for other shapes: client credentials (machine-to-machine, no user — your billing worker authenticates as itself), and the legacy implicit/password flows you should treat as museum pieces.

OIDC: identity on top of OAuth

OAuth 2.0 is deliberately about delegated authorization — it issues access tokens for APIs, and famously does not tell the client who the user is. OpenID Connect adds that missing identity layer: an id_token (a JWT with sub, iss, aud, and profile claims) returned alongside the access token. “Sign in with Google” is OIDC; “let this app read your Google Calendar” is OAuth. They travel together so often that people say “OAuth” and mean both — keep the layers straight: OIDC authenticates the user to the client, OAuth authorizes the client to your API.

Choosing

Scenario Fit
internal tool, webhook sender Basic auth over TLS (or an API key — Ch. 7)
server-rendered web app, one API sessions
mobile/SPA + many API servers short-lived JWT + refresh tokens
third-party apps on your platform OAuth 2.0 auth-code + PKCE
“Log in with X” OIDC
service-to-service, no user OAuth client credentials

Pitfalls

QQuestionSelf-check

Why can’t you revoke a JWT, and what design compensates? In the authorization-code flow, why is the code exchanged server-to-server instead of returning tokens directly to the browser? A teammate proposes storing the user’s role and home address in JWT claims “to avoid database lookups” — what’s wrong?

ASolution

A JWT is valid by signature alone until exp; there is no server-side record to delete. The standard fix is short-lived access tokens (minutes) plus revocable refresh tokens — worst-case exposure shrinks to one token lifetime. The code is exposed to the browser (referer headers, history, malicious extensions); exchanging it requires the client secret (or PKCE verifier), so only the real client can turn a code into tokens, and the tokens never touch the browser’s URL surface. The home address is PII in a signed-but-public payload — anyone holding the token can read it — and roles in a long-lived token go stale when permissions change. Keep claims minimal and non-sensitive; look up the rest.

Next: Authorization Methods (API Design #6) — now that you know who is calling, decide what they’re allowed to do: RBAC, ABAC, ReBAC, and friends.