Authentication and authorization: sessions and JWT
Why you care
Authentication answers "who are you"; authorization answers "what are you allowed to do", and conflating the two is why interviewers keep asking for the difference — because in real code the mix-up ships as a bug: a valid, unexpired JWT that says "user 42 is logged in" gets treated as "user 42 can touch this row", when nothing checked that user 42 owns the row. On the job this is also where "log out" secretly does nothing: a JWT nobody revoked keeps validating on every server for as long as its exp says so, even after the user hits "logout" and the session row is long gone. Get this card wrong and either your app trusts a token nobody can actually kill, or you rebuild sticky sessions and wonder why your API doesn't scale past one box.
Explain like I'm 5
A session is a coat-check ticket: the cloakroom (server) keeps your coat and hands you a numbered ticket, and the ticket means nothing without the cloakroom's record — tear up the record and the ticket is worthless paper, even if you still hold it. A JWT is a sealed, signed letter of introduction: it says who you are and until when, and any office with the same wax-seal stamp can read and trust it without calling the cloakroom back. That's faster and needs no shared room, but there is no cloakroom to raid — burn your own copy of the letter, and every other copy is still a valid letter until the date on it passes.
Core concept
- Authentication confirms identity (login). Authorization confirms permission for a specific action on a specific object. A passed authentication check never implies a passed authorization check.
- A session is opaque server-side state: the client holds only a random id (
secrets.token_urlsafe(32), well above the roughly 64 bits of entropy OWASP's Session Management Cheat Sheet asks for a session id), and the server looks it up on every request. Revocation is instant: delete the row. - A JWT is self-contained: header.payload.signature, base64url-encoded, carrying claims the server can verify without a lookup. RFC 7519's registered claims include
iss(issuer),sub(subject),aud(audience),exp/nbf/iat(time bounds) andjti(a unique id, useful for revocation). None of the claims are secret — they're only signed, not encrypted, so never put a password or PII there. - Revocation is the real trade-off: a "revoked" JWT is still cryptographically valid until
expunless you keep server-side state anyway (a deny-list keyed byjti, checked on every request) — at which point you've paid for the session model's lookup and kept the JWT's complexity. - Every verification checks the signature, and separately, explicitly, the claims: issuer, audience and expiry. Per RFC 8725 (the JWT security best-practices RFC), never trust the token's own
algheader to decide how to verify it — pin the algorithm your server expects, or an attacker can switchRS256toHS256and get your library to check the RSA public key as if it were an HMAC secret, or slip inalg: noneif the library allows it. - Object-level authorization happens after authentication, on every access, not once at login: "is this JWT valid" and "does this JWT's subject own order 4471" are two separate checks, and skipping the second is the single most common access-control bug (Application threat boundaries: SQLi, SSRF and IDOR).
Use sessions when you control the servers your users hit and want instant, simple revocation. Use JWTs when a client needs to prove identity to services you don't run, or when a shared session store would become a single dependency for every one of those services — and treat revocation as something you design for from day one, not a feature you bolt on after the first incident.
Under the hood
A JWT is three base64url segments joined by dots: header.payload.signature. The signature is HMAC-SHA256(header_b64 + "." + payload_b64, secret) (for HS256), computed over the exact transmitted bytes of the first two segments, not the decoded JSON — decode a token, re-encode it with different key order or whitespace, and the signature breaks even though the data is logically identical. This byte-exactness is also the root of the algorithm-confusion attack RFC 8725 warns about: because the header names its own algorithm and many libraries dispatch on it, an attacker holding your RSA public key can craft a token with "alg":"HS256" and hand that public key back as if it were an HMAC secret — a library that blindly follows the header's alg will check it and accept. RFC 8725's fix puts the burden on the caller: pin the expected algorithm in your verifier's configuration, and never branch on the token's own alg field.
Minimal example Sign, verify, and detect one flipped claim
import base64, hashlib, hmac, json, time
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64url(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def sign(header: dict, payload: dict, secret: bytes) -> str:
signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
b64url(json.dumps(payload, separators=(",", ":")).encode())
sig = hmac.new(secret, signing_input.encode(), hashlib.sha256).digest()
return signing_input + "." + b64url(sig)
secret = b"server-only-secret"
header = {"alg": "HS256", "typ": "JWT"}
payload = {"sub": "user-42", "exp": int(time.time()) + 900}
token = sign(header, payload, secret)
print(token.count("."))
h, p, s = token.split(".")
recomputed = hmac.new(secret, f"{h}.{p}".encode(), hashlib.sha256).digest()
print(hmac.compare_digest(unb64url(s), recomputed))
tampered_p = b64url(json.dumps({"sub": "user-999", "exp": payload["exp"]}, separators=(",", ":")).encode())
tampered_check = hmac.new(secret, f"{h}.{tampered_p}".encode(), hashlib.sha256).digest()
print(hmac.compare_digest(unb64url(s), tampered_check))2
True
FalseIn production Session revocation is instant; a JWT needs a deny-list
import base64, hashlib, hmac, json, secrets, time
SECRET = b"server-only-secret-do-not-log"
REVOKED_JTIS = set()
SESSIONS = {} # sid -> {"user": ..., "exp": epoch}: stands in for Redis/Postgres
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64url(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def issue_jwt(user: str, ttl: int = 900):
header = {"alg": "HS256", "typ": "JWT"}
payload = {"iss": "orders-api", "sub": user, "aud": "orders-api",
"iat": int(time.time()), "exp": int(time.time()) + ttl,
"jti": secrets.token_hex(8)}
signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
b64url(json.dumps(payload, separators=(",", ":")).encode())
sig = hmac.new(SECRET, signing_input.encode(), hashlib.sha256).digest()
return signing_input + "." + b64url(sig), payload["jti"]
def verify_jwt(token: str, expected_aud: str):
h, p, s = token.split(".")
expected_sig = hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest()
if not hmac.compare_digest(unb64url(s), expected_sig):
return None
payload = json.loads(unb64url(p))
if payload["aud"] != expected_aud or payload["exp"] < time.time():
return None
if payload["jti"] in REVOKED_JTIS:
return None
return payload
def create_session(user: str, ttl: int = 900) -> str:
sid = secrets.token_urlsafe(32)
SESSIONS[sid] = {"user": user, "exp": time.time() + ttl}
return sid
def logout_session(sid: str) -> None:
SESSIONS.pop(sid, None)
sid = create_session("user-42")
print("session valid before logout:", sid in SESSIONS)
logout_session(sid)
print("session valid after logout:", sid in SESSIONS)
token, jti = issue_jwt("user-42")
print("jwt valid before 'logout':", verify_jwt(token, "orders-api") is not None)
REVOKED_JTIS.add(jti) # this is the server state a "stateless" token secretly needs
print("jwt valid after adding jti to deny-list:", verify_jwt(token, "orders-api") is not None)session valid before logout: True
session valid after logout: False
jwt valid before 'logout': True
jwt valid after adding jti to deny-list: FalseSee it happen Two requests, one lookup, one signature check
- Client authenticates once with credentials.
- Session model: the server creates state and remembers it.
- The client gets only an opaque, unguessable id.
- Every later request carries just the id.
- The API server must ask the store before it trusts anything.
- A revoked sid returns nothing here, instantly.
- JWT model: the same later request instead carries a signed claim set.
- No network call needed, unless the API server also keeps a jti deny-list.
In your world
The situation
Your FastAPI service issues a JWT on login with a 12-hour exp and no jti, because "that's stateless and scales." Logout on the frontend just deletes the token from browser storage.
What actually breaks
A support laptop is compromised at 10am. The stolen JWT, copy-pasted into curl, still authenticates orders until it expires at 10pm — logout on the frontend never touched the server, and there's no way to kill that one token early without killing the shared secret for every user.
What you'd do on Monday
Add jti to every issued token and a real revoked-token table, so an incident response has something to do besides wait:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE revoked_tokens (jti TEXT PRIMARY KEY, revoked_at TEXT)")
def revoke(jti: str) -> None:
conn.execute("INSERT OR REPLACE INTO revoked_tokens VALUES (?, datetime('now'))", (jti,))
conn.commit()
def is_revoked(jti: str) -> bool:
row = conn.execute("SELECT 1 FROM revoked_tokens WHERE jti = ?", (jti,)).fetchone()
return row is not None
stolen_jti = "a1b2c3d4"
print("revoked before incident response:", is_revoked(stolen_jti))
revoke(stolen_jti)
print("revoked after incident response:", is_revoked(stolen_jti))revoked before incident response: False
revoked after incident response: TrueImagine you work at Okta
The numbers
Illustrative: 50M verifications/day ≈ 580/s average, spiking to roughly 5,000/s at a login-heavy peak. If every verification needs a deny-list lookup against a shared store, that's 5,000 extra round trips/s to whatever holds REVOKED_JTIS.
What the Scenario-A answer does here
The Scenario A fix (jti plus a deny-list) still works, but a single shared SQL table checked on every request at 5,000 req/s adds a network hop and lock contention to the hot path of every API server — the fix that saved you from an unkillable token now makes JWT verification no faster than a session lookup.
What flips at this scale
At this scale you keep the deny-list deliberately small and fast: only revoked-before-exp tokens live in it, pruned once their own exp passes (a revoked entry is worthless once the token would have expired anyway), and it sits in a low-latency cache in front of the durable store, never in the request's primary database.
The trade-off you'd defend
I would defend a short-lived, cache-backed deny-list plus a short token exp (minutes, not hours) over either a fully stateless long-lived JWT or a full session-per-request lookup, trading a small cache dependency for both fast verification and revocation that actually works.
Illustrative figures chosen to make the arithmetic concrete; not Okta-published numbers.
Session vs JWT
| Axis | Session (opaque id) | JWT (signed claims) |
|---|---|---|
| Where state lives | Server-side store; client holds only an id | Encoded in the token itself |
| Revocation | Instant: delete the store row | Needs a deny-list or a short exp; not free |
| Cross-service trust | Needs the same store reachable by every service | Any service with the verification key can trust it, no shared store |
| Payload visibility | Nothing exposed to the client | Claims are base64, not encrypted: readable by anyone holding the token |
| Typical use | First-party web app, one team's servers | Cross-service calls, third-party APIs, mobile clients hitting many backends |
Gotchas
Checking the signature but not the claims
A JWT signed by your own auth server for a different audience (say, a partner's API) is accepted by your service and grants access.
A valid signature only proves your key signed it; it says nothing about who the token was meant for. Skipping aud/iss checks, or the object-ownership check, admits the wrong access even though the signature is genuine.
Verify iss, aud and exp as steps separate from the signature, and check object ownership on every access, not just once at login.
Trusting the token's own alg header
An attacker-supplied token with "alg":"HS256" verifies successfully against a service that normally issues RS256 tokens.
The library read the algorithm from the untrusted header and used the RSA public key as if it were an HMAC secret.
Pin the expected algorithm in the verifier's configuration; never branch on the token's own alg field (RFC 8725).
"Logout" that only clears the browser
A copy of the token, pasted into curl, keeps working long after the user logged out.
Deleting client-side storage never touches the server; a JWT with no deny-list stays valid until exp regardless.
Track revocable state by jti (see Scenario A), or keep exp short enough that "log out and wait" is an acceptable answer.
Tricky questions
Yes, since it's cryptographically protected, nobody else can read it.
HMAC/RSA signing proves integrity and origin, not secrecy. Header and payload are only base64url-encoded, not encrypted; anyone holding the token can read every claim. Put nothing sensitive in the payload.
Yes, once you know it's user-42's valid token, you know they're allowed to act.
Authentication confirms identity; a second, explicit check must confirm user-42 owns the specific object being accessed. Skipping it is IDOR (Application threat boundaries: SQLi, SSRF and IDOR).
Scenario question
You're handed a service that authenticates with JWTs and has no logout endpoint at all — "the token just expires." Product now wants an instant "log out of all devices" button. What do you build, and what do you tell them about tokens already issued with a 24-hour exp?
Model answer
I would add a jti to every newly issued token and a token_version (or logged_out_at) claim per user, checked against a small per-user value stored server-side; bumping that value invalidates every token issued before it in one write, without a deny-list entry per token. For tokens already out there with a 24-hour exp and no such claim, I would say plainly that those specific tokens cannot be revoked early — the fix only protects tokens issued after I ship it — and I would separately propose shortening exp to 15-30 minutes with a refresh token (Rotate refresh tokens and retire sessions) so the exposure window for the next incident is minutes, not a day.
Interview corner
CommonWhat's the difference between authentication and authorization?
TrickYou revoke a user's session, but they can still make authenticated calls. Why?
CommonWhat goes in a JWT payload, and what shouldn't?
Experience checkWhere has session-versus-JWT confusion bitten a team you've seen?
DesignWould you use sessions or JWTs for a new internal API?
Memory hook
A session is a coat-check ticket the cloakroom can void; a JWT is a signed letter nobody can un-write, only outlive.
Authenticating proves identity; it never proves the right to touch a specific object — check that separately, every time.
Self-check
What does it mean that a JWT's claims are "signed, not encrypted"?
Anyone holding the token can read the header and payload; the signature only proves who issued it and that it wasn't altered.
Why can't you truly revoke a JWT without extra server state?
Its own validity check is just signature plus time claims; killing one early needs a deny-list or version claim checked server-side, which is the "server state" a session already had.
Name the two claims RFC 8725 says you must never skip, beyond the signature.
iss(issuer) andaud(audience), plus checkingexp.
Take the issue_jwt/verify_jwt pair from this card, add a token_version claim and a per-user version counter in a dict, and implement logout_all_devices(user) that bumps the counter. Show that a token issued before the bump fails verification after it, and a freshly issued token after the bump succeeds. Paste both outputs.