AuthN and AuthZ: Who Are You, and What May You Do
Sessions, JWTs, OAuth, and API keys for robots — and the iron rule: never roll your own crypto, almost never your own auth.
🎯 By the end you'll understand
The exact difference between authentication and authorization, and why conflating them is its own class of bug. How session cookies and JWTs both work — and where JWT revocation breaks down. The OAuth authorization-code flow demystified from first principles. Why password hashing is not encryption. How API keys differ from user tokens. And through the widget, exactly which auth designs contain a stolen credential and which hand over the kingdom.
KEY INSIGHTThe iron rule of auth
Broken authorization — not broken encryption, not SQL injection — is the most common serious vulnerability in real production systems. It is almost always a logic error, not a crypto error.
If you have ever added if user.is_admin: in four different endpoints instead of one place, you have already written broken authorization. If you have stored a plain password in a database column named password, you have already broken authentication. Neither failure requires an attacker with special skills; both show up in the OWASP Top 10 every year because they show up in production code every year.
Authentication (AuthN) answers "who are you?" — it establishes an identity. Authorization (AuthZ) answers "what may you do?" — it enforces a policy on top of that identity. The two are separate concepts, separate code paths, and separate failure modes. Every auth system you build has both, whether you name them or not. The rule you should never violate: never roll your own crypto, and almost never your own auth — use a battle-tested library or service for the identity plumbing, and put your energy into the authorization logic that is actually specific to your system.
DEFINITIONAuthN and AuthZ: two separate problems
The confusion starts because they're always used together, but they answer different questions and fail in different ways.
| Concept | Question answered | Mechanism | Typical failure |
|---|---|---|---|
| Authentication (AuthN) | "Are you who you claim to be?" | Password hash, token signature, certificate, biometric | Credential theft, brute force, session fixation |
| Authorization (AuthZ) | "Are you allowed to do this?" | RBAC, ABAC, ACLs, policy engines | Missing check, wrong object referenced, elevation via parameter tampering |
Here is the real-world failure mode that is embarrassingly common: a service authenticates perfectly — it correctly verifies your JWT signature, confirms you are user #42, and logs the request — then serves you any other user's data if you simply change the ID in the URL. Authentication passed. Authorization never happened. OWASP calls this category "Broken Object Level Authorization" (BOLA, sometimes IDOR — Insecure Direct Object Reference) and it has been in the API Security Top 10 since the list was created.
The pattern: GET /api/runs/1234 returns the run — whoever requests it. A properly authorized endpoint checks that run 1234 belongs to the requesting user. The fix is one line of policy. The miss is infinite access to every object in your database.
Both authn and authz have to be centralized. Every new endpoint that re-implements the check is another place to forget it.
HOW IT WORKSSessions and cookies: the stateful approach
The original web auth model: after the browser sends correct credentials, the server generates a random, unpredictable session ID, stores the session data (user identity, roles, expiry) server-side in memory or a database, and sends the ID to the browser in a Set-Cookie header. Every subsequent request carries the cookie back automatically; the server looks up the session ID, retrieves the live state, and knows who is asking.
The critical security properties of a session cookie: it must be random and unpredictable (a UUID v4 is fine; your user's database ID is catastrophically wrong), it must be set with HttpOnly (no JavaScript access, so XSS cannot steal it), Secure (HTTPS only), and SameSite=Lax or Strict (CSRF mitigation). Miss any of these and your session infrastructure is the attack surface.
The one thing sessions do beautifully that tokens cannot: instant revocation. Delete the session from the store, and the cookie that represents it is immediately worthless — the next request looking it up finds nothing. This matters for "log everyone out" security responses, for ban enforcement, for admin-forced logouts. Token-based systems, as you are about to see, pay a real price for the same guarantee.
HOW IT WORKSJWTs and token auth: stateless but not free
A JSON Web Token (JWT) is a self-contained credential. Instead of handing the client an opaque ID and keeping the real data server-side, the server encodes the user's identity and claims directly in the token, signs it with a secret key (or private key for RS256), and sends it to the client. The client presents the token on every request; the server verifies the signature — no database lookup required. This makes JWTs attractive for distributed systems and microservices: any service that knows the signing key can validate a token independently.
A JWT has three base64url-encoded parts joined by dots: header.payload.signature. The header names the algorithm ({"alg":"HS256","typ":"JWT"}). The payload carries the claims — standard ones like sub (subject/user ID), exp (expiry Unix timestamp), iat (issued at), plus any application-specific claims you add. The signature is HMAC-SHA256(base64(header) + "." + base64(payload), secret). The payload is not encrypted — anyone can decode it. It is only signed — only someone with the secret can produce a valid signature.
{
"sub": "user_42",
"email": "ada@tracelab.dev",
"roles": ["researcher", "viewer"],
"exp": 1749600000, // Unix timestamp — server rejects after this
"iat": 1749513600 // issued-at; exp - iat = 86400s = 24h
}
The signature binds the header and payload together. If you change any byte of the payload — say, upgrading your role from viewer to admin — the signature becomes invalid. The server rejects it. This is the tamper protection the widget will demonstrate.
The statefulness tradeoff cuts both ways. Sessions can be revoked in milliseconds — delete the row. A JWT is valid until it expires, period. You cannot "un-sign" a token you already issued. The moment a user logs out, discloses a compromised token, or gets banned, that JWT keeps working until its exp claim arrives. Solutions exist — token blocklists in Redis, short expiry plus refresh tokens, "jti" claim tracking — but every one of them reintroduces statefulness. If you need instant revocation, you need state somewhere. That is the core tradeoff, and it is not a design flaw you can engineer away.
SEE ITAuth flow step-runner
Walk session login, JWT issuance and expiry, and the OAuth authorization-code flow as message sequences between three parties. Then, for session and JWT flows, try tampering with the token mid-flight and replaying a request — and watch which designs catch which attack.
Three things to absorb. First: in the session flow, a stolen session cookie hands over the kingdom — the server has no way to distinguish the real user from the attacker holding the same ID. In the JWT flow, the server's signature check means a tampered payload is caught — but a stolen valid token still works until expiry. Second: replays against session auth succeed only until the session expires or is revoked; replays against a JWT succeed until the exp claim passes. Third: the OAuth flow adds a third party (the identity provider) and a one-time-use authorization code, which means even if the code is intercepted in the redirect, it is useless without the client secret that only your server holds.
HOW IT WORKSOAuth: the authorization-code dance demystified
OAuth 2.0 is not an authentication protocol — it is an authorization delegation protocol. It answers "may this application act on your behalf?" not "are you who you claim?" The authorization-code flow (the one you should use for server-side apps) involves four distinct roles:
- Resource Owner — the user (e.g., Ada, a TraceLab researcher)
- Client — the application requesting access (TraceLab's web UI)
- Authorization Server — the identity provider (GitHub, Google, your own Keycloak)
- Resource Server — the API holding the protected resources (TraceLab's API server)
The critical insight about the authorization code: it is a one-time-use, short-lived intermediary. The browser sees the code in the redirect URL, but never sees the access token. The code is useless without the client secret, which only the server-side application knows. This is the attack surface the flow is designed to minimize — even if the authorization code leaks (logs, referrer headers, browser history), the attacker cannot exchange it for a token without the client secret they do not have.
For human-facing TraceLab logins, the right answer in 2025 is almost always: use an existing provider. Integrate with GitHub OAuth (your ML researchers already have accounts), or deploy Keycloak or Authentik if you need self-hosted. The authorization-code flow you just learned is the foundation of what those integrations implement. Understanding it means you can debug the redirect mismatches, scope errors, and state parameter confusion that actually shows up in real implementations — without needing to implement it yourself.
The state parameter your client app generates and sends in step ① must be a random, unguessable string stored in the user's session. When the redirect comes back in step ⑤, you verify the state matches. Without it, an attacker can craft a malicious redirect that logs a victim into the attacker's account — a CSRF attack on the OAuth flow itself.
IN PRACTICEAPI keys: credentials for machines
Your TraceLab CLI (a Python script running on a robot) cannot do an OAuth dance — there is no browser, no redirect URI, no human to click "consent." This is the use case for API keys: long-lived, high-entropy secrets that a machine client presents directly in a request header.
import httpx, os TRACELAB_URL = os.getenv("TRACELAB_URL", "http://localhost:8000") # API key lives in an env var — never hardcoded, never in source control API_KEY = os.getenv("TRACELAB_API_KEY") def log_run(run_id: str, metrics: dict) -> dict: resp = httpx.post( f"{TRACELAB_URL}/api/v1/runs", json={"run_id": run_id, "metrics": metrics}, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=10.0, ) resp.raise_for_status() return resp.json()
An API key is conceptually a password for a service account. The security requirements follow from that framing: it must be cryptographically random (not sequential, not guessable), long enough to be impractical to brute-force (32 bytes from secrets.token_urlsafe(32) gives you 256 bits of entropy), stored server-side as a hash (same as passwords — you verify by hashing the presented key and comparing, you never store the raw value), and rotatable without downtime.
Practical API key design decisions that matter:
- Prefix the key with a recognizable string —
tl_live_ortl_test_. This makes the key identifiable in logs and lets secret-scanning tools (like GitHub's push protection) find it if someone accidentally commits it. - Scope keys — a robot arm should get a write-only key for its own project, not read access to every experiment in the database.
- Expiry is a good idea, but you must provide a smooth rotation path. Many systems that say "keys never expire" mean "rotating them is too painful and nobody does it." Make rotation a first-class operation.
CORE CONCEPTPassword hashing: never encryption, always a one-way function
Passwords are the one credential type you should never be able to recover, even as the database owner. This rules out encryption (which is reversible) and plain storage (obviously broken). The right tool is a password hashing function — a slow, deliberately expensive one-way function that maps a password to a fixed-length digest and can never be run backward.
The two functions you should reach for in 2025 are bcrypt and Argon2 (Argon2 won the Password Hashing Competition in 2015 and is the current recommended choice; bcrypt is older but well-studied and still acceptable). Do not use SHA-256, MD5, or any general-purpose cryptographic hash for passwords — those are fast by design, which makes them weak: a modern GPU can test billions of SHA-256 candidates per second. Argon2 and bcrypt are designed to require configurable amounts of time, memory, and parallelism per attempt.
from passlib.context import CryptContext # Use bcrypt or argon2; never sha256_crypt, md5_crypt, etc. pwd_ctx = CryptContext(schemes=["bcrypt"], deprecated="auto") def hash_password(plain: str) -> str: # Returns something like: $2b$12$abc...def — salt is embedded return pwd_ctx.hash(plain) def verify_password(plain: str, hashed: str) -> bool: # Extracts the salt from hashed, re-hashes plain, compares return pwd_ctx.verify(plain, hashed) # NEVER do this: # if user.password == password: # plain storage # if sha256(password) == stored: # fast hash — attackable # if decrypt(stored) == password: # encryption — wrong tool
The salt is crucial and automatic with bcrypt/Argon2: a fresh random value is generated per hash and embedded in the output. This means two users with the same password get different hashes, and pre-computed rainbow tables are useless. The library handles this; you do not generate salts manually.
bcrypt's cost factor (default 12 in most libraries — meaning 2^12 rounds of the key schedule) makes one hash take about 200–400ms on a modern CPU. That is deliberately slow: annoying in bulk, but fast enough for one user login. As hardware gets faster, you increase the factor. This adaptive cost model is why these functions remain secure over time. A raw SHA-256 hash takes under a microsecond — 200,000× faster, and that gap is the attacker's budget.
IN PRACTICERBAC: teams sharing TraceLab runs
Role-Based Access Control is the most common authorization model for applications with human users. Instead of assigning permissions directly to users (fragile, doesn't scale), you assign permissions to roles, and assign users to roles. A user's effective permissions are the union of their roles' permissions. When Ada leaves the team, you remove her user account — all her role memberships and their permissions disappear atomically. When you add a new "admin" permission, you add it to the admin role once — every admin gets it automatically.
| Role | Create runs | Read any run | Delete runs | Manage users | Read others' runs |
|---|---|---|---|---|---|
| admin | ✓ | ✓ | ✓ | ✓ | ✓ |
| researcher | ✓ | own only | own only | — | — |
| viewer | — | own only | — | — | — |
| robot (API key) | ✓ | — | — | — | — |
In FastAPI (TraceLab v2's server framework), this looks like a dependency injected into each endpoint:
from fastapi import Depends, HTTPException, status from .auth import get_current_user def require_role(*roles: str): async def checker(user = Depends(get_current_user)): if not any(r in user.roles for r in roles): raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Insufficient role") return user return checker # Usage — authorization is ONE line per endpoint, not scattered: @app.delete("/api/v1/runs/{run_id}") async def delete_run( run_id: str, user = Depends(require_role("admin", "researcher")), db: AsyncSession = Depends(get_db), ): run = await db.get(Run, run_id) # Object-level check: researcher can only delete own runs if "admin" not in user.roles and run.owner_id != user.id: raise HTTPException(403, "Not your run") await db.delete(run) return {"deleted": run_id}
Note the two-layer check: first the role check (a type authorization), then the object-level ownership check (a resource authorization). Omitting the second layer is exactly the BOLA vulnerability described at the top — a researcher can authenticate as themselves, pass the role check, and delete any other researcher's run by guessing or enumerating IDs.
TRACELABTraceLab v2: adding token auth
TraceLab v2 is a working client–server system. Its HTTP API speaks JSON; its data lives in Postgres; its CLI is a proper client. This lesson contributes the auth layer that makes "who can log what" a real constraint rather than an honor system.
The v2 auth architecture is deliberately pragmatic for a self-hosted research tool:
- Human users authenticate via username/password → server issues a JWT (HS256, 24h expiry) for API use, plus a longer-lived refresh token stored server-side
- Robot/CLI clients use API keys — prefixed, hashed at rest, scoped to create-runs only
- Authorization via the RBAC table above: admin, researcher, viewer, robot
- The object-level check (
run.owner_id == user.id) is enforced in every write endpoint
import secrets, hashlib PREFIX = "tl_live_" def generate_api_key() -> tuple[str, str]: """Returns (raw_key_shown_once, hashed_key_stored_in_db).""" raw = PREFIX + secrets.token_urlsafe(32) hashed = hashlib.sha256(raw.encode()).hexdigest() return raw, hashed def verify_api_key(presented: str, stored_hash: str) -> bool: candidate = hashlib.sha256(presented.encode()).hexdigest() # Use hmac.compare_digest to prevent timing attacks import hmac return hmac.compare_digest(candidate, stored_hash)
One deliberate debt we are carrying into the v2 "God module" (which Stage 4 will dissect): the JWT secret is loaded from an environment variable with no rotation mechanism. That is fine for a research tool today. It is a problem the day you need to rotate the secret without invalidating everyone's session — a real concern once TraceLab has multiple concurrent users running long experiments. The architecture to solve that (short expiry + refresh tokens with a token version field in the database) is Stage 4 material, but naming the debt now is the point.
WEAKNESSWhere auth bites
The most common pattern in internal tools: you add authentication (verify the user), then scatter if user.email == "admin@company.com": checks throughout the codebase. You have no single source of truth for who can do what. The day you need to add a second admin, remove an admin, or audit access, you are grep-and-pray. Authorization logic must be centralized — in a dependency, a middleware, a policy engine — never in ad-hoc conditionals spread across dozens of endpoints.
HTTP 401 Unauthorized means "you need to authenticate — I don't know who you are." HTTP 403 Forbidden means "I know exactly who you are — you are not allowed to do this." These are different. A logged-in user getting refused access to another user's data should get 403. An unauthenticated request should get 401. Returning 401 everywhere leaks the fact that the resource exists (an authenticated user would get 403). Some security-conscious systems return 404 for authorization failures on sensitive resources to avoid confirming existence to unauthorized viewers — a legitimate design choice, but a deliberate one, not an accident.
Early JWT libraries had a catastrophic bug: they trusted the alg field in the token header when verifying. An attacker could set "alg":"none" in their own token and many libraries would skip signature verification entirely. The fix is to specify the expected algorithm explicitly when verifying — never accept whatever the token claims. The python-jose library's algorithms=["HS256"] parameter is not optional decoration; it is the guard against this attack. Modern libraries default to rejecting none, but the principle remains: be explicit about what you accept.
KEY INSIGHTHow this connects
- API Design (3.2) — the HTTP API you designed in Lesson 3.2 is the surface that needs auth. The
Authorization: Bearerheader, 401/403 response semantics, and scope design all map directly to the API contract you built there. - TraceLab v2: Client–Server and the First Race (3.10) — the next lesson integrates the HTTP API, Postgres, and the auth layer built here into a complete running system, then deliberately introduces the concurrent-write race condition the rest of Stage 3 exists to help you fix.
The iron rule this lesson established will be tested every time you add an endpoint, a user role, or a new object type. Authentication is infrastructure; authorization is policy. You can outsource the former to a library or provider; the latter is always your code, always your responsibility, and always the thing attackers read most carefully.
GLOSSARYKey terms
- Authentication (AuthN)
- The process of verifying identity — confirming that the entity presenting credentials is who they claim to be.
- Authorization (AuthZ)
- The process of enforcing access policy — deciding whether a verified identity is permitted to perform a specific action on a specific resource.
- JWT (JSON Web Token)
- A signed, self-contained credential with a header, a base64url-encoded JSON payload of claims, and an HMAC or RSA signature. Stateless: the server needs no database lookup to verify.
- OAuth 2.0 authorization-code flow
- A delegation protocol where a user grants a client application permission to act on their behalf. A short-lived authorization code is exchanged for an access token via a server-to-server backchannel, keeping the token out of the browser.
- RBAC (Role-Based Access Control)
- An authorization model where permissions are assigned to roles, and users are assigned to roles — decoupling individual identity from individual permissions.
- BOLA / IDOR
- Broken Object Level Authorization / Insecure Direct Object Reference. A vulnerability where an API authorizes at the type level (correct role) but not the object level (is this specific object yours?), letting authenticated users access any object by guessing its ID.
- Password hashing function
- A deliberately slow, one-way function (bcrypt, Argon2) that maps a password to a salted digest. Unlike general cryptographic hashes, these are tunable to remain expensive as hardware improves.
- API key
- A long, random, machine-issued credential scoped to a service account. Stored server-side as a hash; presented by the client in the Authorization header. The machine-client equivalent of a username/password.
ACTIVE RECALLCheck your understanding
Answer in your own words first, then reveal.
1Your API correctly verifies every JWT signature. A researcher calls GET /api/runs/9999 and gets someone else's data. What went wrong, and what is the OWASP name for this class of bug?›
Authentication worked — the JWT signature was valid and the user was correctly identified. Authorization failed — the endpoint never checked that run 9999 belongs to the requesting user. This is BOLA (Broken Object Level Authorization), also called IDOR (Insecure Direct Object Reference). The fix: after fetching the run, verify run.owner_id == current_user.id (or allow admins). Every endpoint that returns or modifies a user-owned resource must include this check.
2Why can't you simply "revoke" a JWT when a user logs out, and what are the tradeoffs of the approaches that work?›
A JWT is valid by mathematical property — it has a valid signature and a future expiry. You cannot un-sign it. When a user "logs out," the token still works until exp passes. The approaches that work all reintroduce statefulness: (1) a token blocklist in Redis — you add the jti (JWT ID) on logout and check it on every request; (2) short access token expiry (5–15 min) plus a longer-lived refresh token stored server-side — logout invalidates the refresh token, and the access token expires quickly on its own; (3) a token version field per user in the database — each JWT carries the version, and any issued token with an old version is rejected. None of these are free: they all require a database or cache hit per request, partially negating the stateless benefit of JWTs.
3In the OAuth authorization-code flow, why is it safe for the authorization code to appear in a browser redirect URL (and potentially in logs, referrer headers, browser history)?›
Because the authorization code is useless alone. To exchange it for an access token, the server must call the authorization server's token endpoint with both the code and the client secret. The client secret is known only to the server-side application — it is never exposed to the browser. An attacker who captures only the authorization code cannot complete the exchange. This is the purpose of the two-step design: the public channel (browser redirect) carries a code; the confidential channel (server-to-server POST) carries the secret.
4Why should password hashing use bcrypt or Argon2 instead of SHA-256, and what does "the work factor" mean?›
SHA-256 is a general-purpose cryptographic hash optimized for speed — a modern GPU can compute billions per second, making brute-force of a leaked hash database feasible. bcrypt and Argon2 are deliberately slow by design: they introduce a configurable "work factor" (bcrypt's cost parameter, Argon2's time/memory/parallelism parameters) that forces each verification to take a fixed amount of time or memory. On a modern CPU, bcrypt at cost 12 takes ~200ms — a legitimate login barely notices; an attacker trying millions of candidates hits a wall. As hardware improves, you increase the work factor and rehash passwords on next login. The adaptive cost model is what makes these functions durable over time.