AuthN vs AuthZ: sessions, JWT, OAuth
Authentication proves who you are and authorization decides what you may do: log in with OIDC (auth code + PKCE), carry identity in short-lived tokens or sessions, and check permissions server-side on every request.
Analogy: A hotel desk checks your passport once and hands you a key card. The card opens your room and the gym, not the kitchen, and dies at checkout.
How it works
- A failed authN is
401(who are you?); a failed authZ is403(known, but not allowed). - Sessions revoke instantly but need a lookup; JWTs verify locally but stay valid until
exp. - OAuth delegates access to an API; OIDC adds a signed ID token that says who signed in.
- PKCE sends a hash of a secret, then the secret at code exchange: a stolen code is useless.
- Model permissions with RBAC, ABAC or ReBAC; enforce where the data lives, and deny by default.
Check yourself
Answer to mark it learned; your answers aren't scored.
Security requires that a fired employee lose API access within a minute. Your services verify 1-hour JWT access tokens locally, with no call to the identity provider. What do you change?
Go deeper
Full explanation
Authentication (authN) proves identity; authorization (authZ) decides access. Failing the first is 401, the second 403.
Carrying identity:
- Server sessions: a random id in an
HttpOnly,Secure,SameSitecookie; the server looks it up. Revocation is instant: delete the row. - JWT: signed claims (
iss,sub,aud,exp) that any service verifies without a lookup. Signed, not encrypted: anyone can read them. It stays valid untilexp, so keep access tokens short and refresh them.
OAuth 2.0 delegates access: an app gets a scoped access token for an API. OIDC adds identity with a signed ID token. To sign users in, use the authorization code flow with PKCE: the app sends a hash of a random secret, then proves it holds the secret when redeeming the code, so an intercepted code is useless. RFC 9700 (2025) bans the password grant and steers away from the implicit grant.
Authorization models: RBAC maps roles to permissions; ABAC evaluates attributes (tenant, owner, amount); ReBAC follows relationships, as in Google's Zanzibar. Enforce in the service that owns the data, deny by default.
Code Verify a JWT, then authorize the action
import jwt
from jwt import PyJWKClient
ISSUER = "https://idp.example.com" # your OIDC provider
AUDIENCE = "orders-api" # this API, not any API
jwks = PyJWKClient(f"{ISSUER}/.well-known/jwks.json") # caches the key set (5 min)
def authenticate(token: str) -> dict:
key = jwks.get_signing_key_from_jwt(token)
return jwt.decode( # raises on bad signature, aud, iss, exp
token, key,
algorithms=["RS256"], # pinned: never trust the token's own alg
audience=AUDIENCE, issuer=ISSUER,
options={"require": ["exp", "iss", "aud", "sub"]},
)
def authorize(claims: dict, action: str, order: dict) -> bool:
if claims.get("tenant_id") != order["tenant_id"]:
return False # ABAC: tenant is a hard rule
roles = set(claims.get("roles", []))
if action == "read":
return "viewer" in roles or claims["sub"] == order["owner_id"]
if action == "refund":
return "support_admin" in roles and order["amount"] <= 500
return False # deny by default
def get_order(token: str, order_id: str) -> dict:
claims = authenticate(token) # failure -> 401
order = load_order(order_id)
if not authorize(claims, "read", order):
raise PermissionError("forbidden") # -> 403
return orderReal example
A B2B SaaS on Amazon Cognito keeps the defaults: 1-hour access tokens, 30-day refresh tokens. An employee is fired at 10:00; disabling the user stops new refreshes, but the APIs verify JWTs locally and accept the old token until it expires. The fix: 5-minute access tokens, revoked refresh tokens, and a jti deny-list checked only on sensitive calls (refunds, exports). A separate audit finds the classic bug: changing /orders/123 to /orders/124 returned another tenant's order. A tenant check in every query closed it.
Trade-offs +3 · −3
+ You gain
- OIDC hands login, MFA and SSO to a provider: you never store passwords.
- JWTs let any service verify identity locally, with no auth call per request.
- An explicit model (RBAC, ABAC, ReBAC) makes permissions testable and auditable.
− You pay
- A JWT can't be revoked before
expwithout adding back a lookup (deny-list or introspection). - OAuth has many flows and knobs; misconfigured redirect URIs,
audoralgcause real breaches. - Fine-grained authZ needs a policy engine and fresh data at check time: more latency and moving parts.
Use it when
Every multi-user system. Sessions for a first-party web app; OIDC plus short-lived JWTs when many services or third parties verify identity; ABAC or ReBAC once sharing and tenancy outgrow roles.
Avoid it when
Skip JWTs when one backend serves one browser app: a session cookie is simpler and revocable. Never hand-roll login, password hashing or token crypto.
Numbers to know 4
- PKCE (RFC 7636, 2015): verifier of 43–128 chars; challenge = base64url(SHA-256(verifier)).
- RFC 9700 (OAuth security BCP, Jan 2025): public clients MUST use PKCE; the password grant MUST NOT be used.
- Amazon Cognito defaults (checked Nov 2026): access and ID tokens 1 hour, refresh tokens 30 days.
- Google Zanzibar (2019): trillions of ACLs, millions of checks/s, p95 under 10 ms.
Common pitfalls 4
- Letting the token's
algheader choose verification:noneor an RS256→HS256 swap forges tokens. Pin algorithms. - Not checking
aud: a token minted for another API is accepted by yours. - Checking roles but not ownership:
/orders/124returns another tenant's data (broken object-level authorization). - Authorizing only in the frontend or gateway: any direct call to the service skips it.
Interview questions 3
Answer out loud first, then reveal.
JWTs or server sessions?Show answer
For a first-party web app on one backend, sessions: a random id in an HttpOnly cookie, one Redis lookup, and logout or a ban is instant. JWTs pay off when many services or third parties verify identity without calling an auth service. The price is revocation: a JWT lives until exp. So I keep access tokens to minutes, rotate refresh tokens, and add a deny-list only for high-risk actions.
How would you model permissions for a multi-tenant document app with sharing?Show answer
Roles alone break with sharing: "editor of doc 42, viewer of folder 7" explodes into per-object roles. I'd keep RBAC for coarse admin roles and model sharing as relationships, ReBAC like Zanzibar: user, member of team, editor of folder, parent of doc. The tenant id stays a hard ABAC rule on every query. One policy engine defines the rules, each service enforces them, deny by default, and every decision is logged.
Why PKCE if you already use the authorization code flow?Show answer
Because the code travels through the browser, where a malicious app on the same redirect scheme, a leaky redirect or logs can grab it. Without PKCE, whoever holds the code can redeem it. With PKCE the app first sends SHA-256(verifier) and must present the verifier itself, which never left the app, at the token endpoint. RFC 9700 requires it for public clients and recommends it for confidential ones, so I use it everywhere.