Authentication & Authorization
Proving identity and controlling access — sessions and cookies, JWTs and their trade-offs, OAuth 2.0 and OpenID Connect flows (authorization code + PKCE), SSO, MFA and passkeys, API keys, and authorization models (RBAC, ABAC, ReBAC).
Two different questions:
- Authentication (authn): who are you? — verifying identity (password, passkey, SSO).
- Authorization (authz): what may you do? — checking permissions for each action.
HTTP is stateless, so after login the server needs a way to recognise subsequent requests: sessions or tokens.
Password login done right
- Store passwords with a slow, salted hash — Argon2id, bcrypt or scrypt — never plain text or fast hashes like SHA-256 (Password storage).
- Rate-limit login attempts and add lockouts or CAPTCHA after failures; check passwords against breach lists.
- Return the same error for "unknown user" and "wrong password" to avoid account enumeration.
- Offer multi-factor authentication.
Session-based authentication
The cookie holds only a random, unguessable session ID; the data lives on the server (Redis, a database).
| Cookie attribute | Purpose |
|---|---|
HttpOnly | JavaScript can't read it — limits XSS token theft |
Secure | Sent only over HTTPS |
SameSite=Lax / Strict | Not sent on most cross-site requests — CSRF defence (Web security) |
Max-Age / Expires | Lifetime |
Path, Domain | Scope; prefix __Host- to lock it to one origin |
Pros: easy revocation (delete the session), small cookie, server controls everything. Cons: needs a shared session store when scaling horizontally. Regenerate the session ID on login (prevents session fixation).
Token-based authentication and JWT
A JSON Web Token is a signed, self-contained token: header.payload.signature, each Base64URL-encoded.
eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiI3Iiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzY0ODAwMDAwfQ.MEUCIQ…
Header: { "alg": "ES256", "typ": "JWT" }
Payload: { "sub": "7", "role": "admin", "iss": "auth.acme.com", "aud": "api.acme.com", "exp": 1764800000 }
Signature: sign(header + "." + payload, private key)The server verifies the signature and reads claims without a database lookup — useful for stateless APIs and microservices, where any service with the public key can verify (Digital signatures).
Access and refresh tokens
- Access token: short-lived, sent with every API call (
Authorization: Bearer …). - Refresh token: long-lived, stored securely, used only to get new access tokens. Rotate it on each use and detect reuse (a sign of theft).
Sessions vs JWTs
| Server sessions | JWTs | |
|---|---|---|
| State | On the server | In the token |
| Revocation | Immediate | Hard; short expiry + refresh |
| Scaling | Shared store (Redis) | Stateless verification |
| Best for | Traditional web apps | APIs, mobile, service-to-service, federated identity |
For a single web app, cookie sessions are usually simpler and safer. JWTs shine when tokens must cross trust boundaries.
OAuth 2.0 and OpenID Connect
OAuth 2.0 is a framework for delegated authorization: letting an app access a user's resources at another service without seeing their password ("Allow PhotoPrinter to read your Google Photos"). OpenID Connect (OIDC) adds an identity layer on top — an ID token (a JWT) saying who the user is — and powers "Sign in with Google/Microsoft/GitHub" and enterprise SSO.
| Role | Example |
|---|---|
| Resource owner | The user |
| Client | The app wanting access |
| Authorization server | Google's or Okta's login and consent service |
| Resource server | The API holding the data |
Authorization code flow with PKCE
The recommended flow for web, mobile and single-page apps:
- PKCE (Proof Key for Code Exchange): the client sends a hash of a random secret (
code_challenge) at the start and the secret itself (code_verifier) when redeeming the code, so an intercepted code is useless. - The
stateparameter (and OIDC'snonce) prevent CSRF and replay. - Older flows — implicit and password grant — are deprecated. Machine-to-machine uses the client credentials flow; TVs and CLIs use the device code flow.
Scopes limit what a token can do (read:photos). OAuth is not authentication by itself — use OIDC's ID token for identity.
SSO
Single sign-on lets users log in once with a central identity provider (Okta, Entra ID, Google Workspace, Keycloak) and access many apps, via OIDC or the older XML-based SAML. Companies get central offboarding and policy; SCIM syncs user provisioning.
Multi-factor authentication and passkeys
MFA combines factors: something you know (password), have (phone, security key), are (biometric).
| Method | Strength |
|---|---|
| SMS codes | Weak — SIM swapping, phishing |
| TOTP apps (6-digit codes) | Good, but phishable |
| Push approval | Good; vulnerable to "MFA fatigue" spam |
| Passkeys / WebAuthn / FIDO2 security keys | Strongest — phishing-resistant |
Passkeys replace passwords with public-key cryptography: the device holds a private key per site, unlocked with biometrics or a PIN; the server stores only the public key. The browser binds each credential to the site's origin, so a phishing site can't use it, and there's no shared secret to leak in a breach.
API keys
Simple secret strings for server-to-server access or developer APIs. Store only a hash of the key, show it once, allow rotation and scoping, prefix it for leak detection (sk_live_…), and never ship keys in front-end code.
Authorization models
| Model | Idea | Example |
|---|---|---|
| RBAC — role-based | Users get roles; roles have permissions | admin, editor, viewer |
| ABAC — attribute-based | Policies over user, resource and context attributes | "Managers can approve expenses under ₹1L in their own department during business hours" |
| ReBAC — relationship-based | Permissions follow relationships in a graph | Google Docs: owner/editor/viewer of a doc or its folder (Zanzibar; OpenFGA, SpiceDB) |
| ACLs | Per-resource lists of who can do what | File permissions |
Rules that prevent most authz bugs:
- Deny by default; check permissions on the server for every request, never just hide buttons in the UI.
- Check object-level access:
GET /invoices/123must verify that invoice 123 belongs to the caller. Missing checks (IDOR / broken object-level authorization) are the top API vulnerability. - Centralise policy (middleware, a policy engine like OPA or Cedar) rather than scattering
ifchecks. - Principle of least privilege.
- Authentication proves identity; authorization decides permissions — check both server-side on every request.
- Sessions: random ID in an HttpOnly, Secure, SameSite cookie; state on the server; easy revocation.
- JWTs: signed, readable claims for stateless verification; short-lived access tokens, rotating refresh tokens, strict validation.
- OAuth 2.0 delegates access; OIDC adds identity; use authorization code + PKCE.
- Passkeys (WebAuthn) are phishing-resistant and remove shared secrets.
- RBAC, ABAC and ReBAC model permissions; always enforce object-level checks (avoid IDOR).
QShould a web app use sessions or JWTs?medium
For a typical server-rendered or single-domain web app, cookie-based sessions are simpler and safer: the server can revoke them instantly and the cookie is HttpOnly. JWTs suit stateless APIs, mobile clients, microservices and federation, where tokens are verified by services that don't share a session store. If you use JWTs, keep access tokens short-lived, use rotating refresh tokens, validate algorithm, expiry, issuer and audience, and avoid storing them in localStorage.
QExplain the OAuth authorization code flow with PKCE.hard
The client creates a random code_verifier and sends its SHA-256 hash (code_challenge) when redirecting the user to the authorization server. The user logs in and consents; the server redirects back with a short-lived authorization code. The client exchanges the code plus the original code_verifier at the token endpoint; the server checks that the verifier hashes to the challenge before issuing tokens. An attacker who intercepts the code can't redeem it without the verifier. The state parameter protects the redirect against CSRF.