Authentication and Authorisation
Authentication answers who are you. Authorisation answers what may you do. Confusing them
produces two of the most common vulnerabilities: a valid session treated as permission to read any
record, and a 403 returned to a client that should have received 401.
The 60-second answer
Section titled “The 60-second answer”Authentication establishes identity; authorisation checks permission against a resource. Sessions keep state server-side and give the client an opaque id in an HttpOnly cookie, so revocation is instant. Tokens keep state in a signed credential, which is stateless and scales across services but is hard to revoke, so access tokens are short-lived and refresh tokens rotate. Passwords are stored with argon2id or bcrypt, never encrypted. OAuth 2.0 delegates access; OIDC adds identity.
Sessions vs tokens
Section titled “Sessions vs tokens”| Server session | Self-contained token (JWT) | |
|---|---|---|
| State lives | Server store (Redis, DB) | Inside the token |
| Client holds | Opaque id | Signed claims |
| Revocation | Delete the session, immediate | Deny-list or short TTL |
| Scaling | Shared store or sticky sessions | Any node can verify |
| Browser safety | HttpOnly cookie, unreadable by JS | localStorage is readable by any script |
A session cookie is the right default for a browser app: random, high-entropy, meaningless to the
client, sent automatically, unreadable by JavaScript with HttpOnly.
Tokens earn their place when the verifier is not the issuer: many services, mobile clients, third-party APIs, or an edge layer that must authorise without a database call.
JWT structure
Section titled “JWT structure”Three base64url segments: header, payload, signature.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiI0MiIsImV4cCI6MTcwMDAwMDAwMH0 . 3f9c...{ "sub": "42", "iss": "https://auth.example.com", "aud": "api", "exp": 1700000000, "iat": 1699999700, "scope": "orders:read" }- Base64url is encoding, not encryption. Anyone can read the payload; never put secrets or personal data in one.
HS256signs with a shared secret;RS256/ES256sign with a private key so many services can verify with the public key.- Verification must check the signature,
algagainst an allow-list,exp,nbf,issandaud. Skippingaudlets a token minted for one service be replayed against another. alg: noneis a historic attack: a library that trusts the header accepts an unsigned token. Pin the expected algorithm server-side.
JWT pitfalls
Section titled “JWT pitfalls”- No revocation. A stolen token is valid until
exp. Use short lifetimes, refresh rotation, and ajtideny-list for high-risk actions (password change, logout-all). - Stale claims. Roles embedded in a token do not change when revoked. Keep fast-changing authorisation data out of the token, or accept a short TTL.
- Clock skew.
expchecks fail across drifting machines; allow small leeway and backdateiat. - Tokens in URLs. Query strings leak into logs,
Refererheaders and browser history. - Long-lived mobile tokens. Refresh tokens belong in the platform keychain with rotation and reuse detection: presenting an old refresh token revokes the whole family.
OAuth 2.0 and OIDC
Section titled “OAuth 2.0 and OIDC”OAuth 2.0 is delegated authorisation: a user grants a third party scoped access without sharing a password. It is not authentication; OIDC adds that by issuing an ID token.
Roles: resource owner (user), client (app), authorisation server (issues tokens), resource server (holds the data).
Authorisation code flow with PKCE:
1. Client generates code_verifier, computes code_challenge = S256(verifier)2. Browser → /authorize?response_type=code&client_id=...&redirect_uri=... &scope=openid%20profile&state=xyz&code_challenge=...&code_challenge_method=S2563. User authenticates at the IdP, consents4. Browser ← 302 to redirect_uri?code=AUTH_CODE&state=xyz5. Client verifies state, POSTs /token with code + code_verifier6. Server → { access_token, refresh_token, id_token }7. Client calls the API with Authorization: Bearer <access_token>Why each piece exists:
statestops CSRF on the redirect: an attacker cannot complete a flow they started in your browser.- PKCE binds the code to the client that started the flow, so an intercepted code is useless without the verifier. Required for public clients, recommended for all.
redirect_uriallow-listing stops tokens being sent to an attacker’s domain.
| Grant | Use | Status |
|---|---|---|
| Authorization code + PKCE | Web, mobile, SPA | The default |
| Client credentials | Machine-to-machine | Standard |
| Device code | TVs, CLIs | Standard |
| Implicit | Legacy SPAs | Deprecated; tokens in the URL fragment |
| Password | Legacy | Deprecated; the client sees the password |
OIDC adds the openid scope and an ID token: a JWT with sub, iss, aud, exp stating who
the user is. The access token is what the resource server accepts; do not use one as proof of
identity or the other to call APIs. Discovery lives at /.well-known/openid-configuration, public
keys at jwks.json.
SSO is the same flow where the IdP holds a session cookie: log in once, and subsequent apps get a code without a prompt. SAML is the XML enterprise predecessor; OIDC is the modern default.
Password storage
Section titled “Password storage”Passwords are hashed with a slow, salted, memory-hard function — never encrypted, never plain SHA-256.
| Algorithm | Notes |
|---|---|
| argon2id | Current recommendation; memory-hard, resists GPU cracking |
| bcrypt | Battle-tested; cost factor sets work. Truncates input at 72 bytes |
| scrypt | Memory-hard, older, fine |
| PBKDF2 | Only when FIPS compliance demands it |
Each hash carries its parameters, so you can raise cost over time and rehash on next login. The salt is per user and need not be secret.
if Argon2.verify_password(stored_hash, params[:password]) session[:user_id] = user.id user.update!(password_hash: Argon2::Password.create(params[:password])) if needs_rehash?(stored_hash)endHash on the server, compare in constant time, and return the same error and latency for “no such user” and “wrong password” — otherwise you have a user enumeration oracle.
- TOTP (RFC 6238): shared secret plus a 30-second window, six digits. Phishable in real time, cheap, widely supported.
- WebAuthn / passkeys: public-key credentials bound to an origin. Phishing-resistant, because the browser will not sign a challenge for a different domain. The strongest option.
- SMS OTP: defeated by SIM swapping and interception; never the only second factor for high-value accounts.
- Recovery codes: single-use, hashed at rest, the thing that prevents permanent lockout.
Use step-up authentication — a fresh factor before changing a password, adding a payment method or viewing audit logs — rather than treating MFA as a login checkbox.
Authorisation models
Section titled “Authorisation models”RBAC — roles map to permission sets. Simple and auditable; breaks when permissions depend on attributes (“editors may edit only their team’s documents”), which causes role explosion.
ABAC — policies over attributes of subject, resource, action and environment. Expressive, handles context, harder to audit. Common in policy engines such as OPA.
ReBAC — relationships (“owner of”, “member of”) modelled explicitly, as in Google Zanzibar. Useful for sharing graphs.
Regardless of model: enforce on the server for every request and every object; check object-level ownership, not just the endpoint; deny by default; and put the check next to the data access, not only in a controller filter a new route can bypass.
Follow-up questions
Section titled “Follow-up questions”- How do you log a user out of every device when tokens are stateless?
- Where do you store the access token in a SPA, and what does each choice expose?
- How would you implement “admin reads any account, support reads with an audit trail”?
- Why does PKCE matter for a confidential client that holds a secret?
- How do you migrate from bcrypt to argon2id without forcing a password reset?
Common traps
Section titled “Common traps”- “JWTs are encrypted.” They are signed; the payload is public.
- “OAuth is for login.” OAuth is authorisation. Using an access token as identity is the confused-deputy pattern.
- “Sessions do not scale.” They scale fine with a shared store; in-process memory does not.
- “Validation means decoding.”
jwt.decodewithout signature verification is not validation. - “Role checks are enough.” Roles answer “may this class of user do this verb”; you still need per-object checks.