Summary#
Every request to a system raises two questions.
- Authentication (authn) asks: who is this? The caller proves an identity with something they know (a password), something they have (a phone, a security key), or something they are (a fingerprint), or, for software, with a key or certificate.
- Authorization (authz) asks: is this identity allowed to do this, to this resource, right now?
Authentication happens once at login, and it produces a credential that is carried on later requests. That credential is either a session ID in a cookie, which the server looks up, or a token, often a signed JWT, which the server verifies without a lookup. OAuth 2.0 lets an application obtain a token to act on a user's behalf without seeing the user's password. OpenID Connect adds identity on top of it, and that is how "Sign in with Google" and enterprise single sign-on work.
Other credentials cover other callers.
- Machines use API keys or OAuth client credentials.
- Services inside a system prove their identity to each other with mutual TLS.
- Passkeys (WebAuthn) replace passwords with phishing-resistant public-key credentials.
Authorization models grow with need. RBAC maps users to roles and roles to permissions. ABAC evaluates attributes in policies. ReBAC derives access from relationships ("Alice is an editor of the folder that contains this document"), as Google's Zanzibar system does at global scale. A good permission system denies by default, checks every request close to the data, and records every decision that matters.
Why It Exists#
Systems hold things worth protecting: personal data, money, private messages, company secrets, the ability to change configuration. Without authentication, anyone can claim to be anyone. Without authorization, any authenticated user can do anything, such as read another user's messages by changing an ID in a URL.
Failures here dominate security incident reports.
- Broken object-level authorization (an API returning
/orders/1235to a user who owns only order 1234) is first on the OWASP API Security Top 10 list. - Broken authentication, stolen credentials and leaked API keys are among the commonest ways into systems.
Getting the identity layer right is a design problem, not only a coding one. Where do credentials live? How are they revoked? How does identity flow through 30 microservices? How do permissions scale to billions of objects?
How It Works#
Authentication vs authorization#
Authentication establishes the identity of a principal: a user, a service, a device. It answers "who?" The result is an authenticated identity, such as "user 123, logged in 10 minutes ago with a password plus a one-time code".
Authorization decides whether that principal may perform an action on a resource. It answers "may they?" The inputs are the principal, the action (read, update, delete, approve), the resource (booking 987), and sometimes context (time, network location, how recently the user authenticated). The output is allow or deny.
Take a ticket-booking system. Authentication verifies that the request comes from john@example.com. Authorization checks that John may cancel this booking. He may cancel his own bookings, but not other people's. Venue managers may see sales for their venues. Administrators may do almost anything, with an audit trail.
They're separate concerns, often built by separate components.
- An identity provider (IdP) handles authentication. That might be your own login service, or Okta, Auth0, Microsoft Entra ID, Google or Keycloak.
- Authorization logic lives with the application, or in a dedicated policy service.
The boundary matters, because each concern changes for different reasons. Login methods change (passkeys arrive), and permission rules change (a new "billing admin" role), and neither change should force a rewrite of the other.
HTTP keeps them separate too.
- 401 Unauthorized (despite its name) means not authenticated: missing or invalid credentials. The response should carry a
WWW-Authenticateheader naming the scheme. - 403 Forbidden means authenticated, but not allowed.
- Many APIs return 404 Not Found instead of 403 for resources that the caller isn't allowed even to know exist. That avoids leaking, for example, whether a private repository exists.
Authentication, in depth: factors, MFA and account security#
Authentication factors fall into three classes.
- Knowledge: a password or PIN.
- Possession: a phone receiving a code, an authenticator app, a hardware security key, a device holding a passkey.
- Inherence: biometrics. These are usually used locally, to unlock a possession factor (a fingerprint unlocks the passkey on a phone), rather than sent to servers.
Multi-factor authentication (MFA) requires factors from two or more classes, so a stolen password alone isn't enough. MFA methods differ a lot in strength.
- SMS codes are the weakest common option. They are vulnerable to SIM-swap attacks and interception, and to phishing, because a user can be tricked into typing the code into a fake site.
- TOTP authenticator apps (Google Authenticator, Authy, 1Password) implement RFC 6238, the time-based one-time password. The server and the app share a secret, exchanged once through a QR code. Each side computes HMAC(secret, floor(unix_time ÷ 30)), and truncates the result to 6 digits. The codes match if the clocks roughly agree. Servers usually accept one adjacent 30-second step, to tolerate clock drift. TOTP resists SIM swaps, but it is still phishable.
- Push approvals ("Is this you? Approve or deny") are convenient, but they invite "MFA fatigue" attacks, where an attacker floods the user with prompts until they tap approve. Number matching mitigates this: the user types a number shown on the login screen.
- FIDO2 security keys and passkeys are phishing-resistant, because the credential is bound to the website's origin, as explained below. They are the strongest option widely available.
Password handling belongs in Security Fundamentals for System Design: hash with a slow, salted function such as Argon2id, scrypt or bcrypt, and never store or log plaintext passwords. At the design level:
- check new passwords against lists of known breached passwords (NIST SP 800-63B recommends this, and recommends against forced periodic rotation);
- rate-limit login attempts per account and per IP;
- use the same generic error for "unknown user" and "wrong password", so attackers can't enumerate accounts.
Account recovery is part of authentication. A strong login with a weak "forgot password" flow is weak. Recovery links should be single-use, short-lived (15–60 minutes), and bound to the account. They should be sent only to verified contacts, and they should invalidate existing sessions after a password reset. Rate-limit recovery requests (Rate Limiting and Throttling), because they are a favourite target for abuse.
Step-up authentication. Some actions deserve fresh proof even within a valid session: changing the email address or password, viewing an API secret, transferring money. Require re-authentication, or a second factor, if the last authentication is older than a few minutes. OIDC carries this information in the auth_time and acr (authentication context) claims.
Sessions and cookies vs tokens#
After login, the server must recognise the user on later requests without asking for the password again. There are two broad approaches.
Server-side sessions. On login, the server creates a session record, such as session:9f8a… → { user: 123, created, expires, mfa: true }, in a store: Redis, a database, or memory on a single server. It sends the browser a session ID, a long random string, in a cookie. The browser automatically sends the cookie with every request to that site. The server looks up the session ID, and finds the user.
- Pros: revocation is instant (delete the record). Sessions are small (the cookie holds only an ID). The server controls everything, and session data never leaves the server.
- Cons: every request needs a session lookup, typically a Redis read of about 1 ms. The session store must be shared by all servers, and must be highly available. Cross-domain use is awkward, because cookies are tied to domains.
Self-contained tokens. On login, the server issues a signed token containing the claims themselves: user ID, roles, expiry. The client sends it on each request, usually in an Authorization: Bearer <token> header. Any server holding the verification key can check the signature and read the claims, with no lookup. JWT is the common format.
- Pros: stateless verification scales easily, and works across services and domains. Each microservice can verify a token independently. Tokens suit mobile apps and APIs, which don't use cookies naturally.
- Cons: revocation is hard, because a valid token stays valid until it expires unless you add a lookup, which reintroduces state. Tokens are bigger (hundreds of bytes to a few KB). Claims can go stale, as when the user's role changed after the token was issued.
The two aren't exclusive, and the line between them is blurry. A cookie is a transport: a browser mechanism for sending data automatically. A session or a token is the thing that is sent. You can put a JWT in a cookie, or a session ID in a header. The real design choice is between reference credentials, which are looked up on the server (sessions, opaque tokens), and value credentials, which carry signed claims (JWTs).
Sessions and tokens, in depth: cookie security, storage and revocation#
Cookie attributes do real security work.
HttpOnlykeeps JavaScript from reading the cookie, so an XSS bug can't steal the session ID directly.Securesends the cookie only over HTTPS.SameSite=Lax(the browser default in modern Chrome) orStrictstops the browser sending the cookie on most cross-site requests. That is the main defence against CSRF (cross-site request forgery), where a malicious page makes your browser send an authenticated request to another site. Add anti-CSRF tokens for state-changing requests if you needSameSite=None, for example for cross-site embeds.- The
__Host-name prefix forcesSecure,Path=/and noDomainattribute, so subdomains can't overwrite the cookie. - Set a sensible
Max-Age. Rotate the session ID on login and on privilege changes, to prevent session fixation, where an attacker plants a known session ID before the victim logs in.
Where should a browser app keep tokens? JavaScript-readable storage (localStorage, sessionStorage) is exposed to any XSS bug, which can exfiltrate the token and use it from anywhere. HttpOnly cookies are invisible to scripts, though XSS can still use them while the page is open. Current guidance for single-page apps (the IETF's OAuth for browser-based apps draft) favours a backend-for-frontend (BFF). A small server-side component holds the OAuth tokens, and gives the browser only an HttpOnly session cookie, so tokens never reach JavaScript. Mobile apps keep tokens in the platform's secure storage (iOS Keychain, Android Keystore).
Session stores at scale. Take 50 million active sessions at about 500 bytes each. That is about 25 GB in Redis, which a small cluster holds easily. At 100,000 requests per second, session lookups are 100,000 Redis reads a second, which is a handful of shards. Sessions are rarely the bottleneck. The design work is availability: replicate the store, and decide what happens when it fails. If the session store is down, nobody is logged in.
Revocation strategies for tokens.
- Short-lived access tokens plus refresh tokens: access tokens live 5–15 minutes. Longer-lived refresh tokens, which are stored server-side and revocable, get new access tokens. Revocation takes effect within one access-token lifetime.
- A denylist of revoked token IDs (
jti), held until each token's expiry, and checked on each request. Since only revoked tokens are listed, the list is small, and can be cached or pushed to services. - A per-user "valid after" timestamp: reject tokens issued before the user's last logout or password change. This means one small lookup per user, which is cacheable.
- Opaque tokens with introspection: the resource server asks the authorization server whether a token is valid (RFC 7662). Revocation is instant, at the cost of a lookup, usually cached for seconds.
Refresh-token rotation. Each use of a refresh token returns a new refresh token, and invalidates the old one. If an old refresh token is ever presented again, someone has copied it. The server then revokes the whole token family, logging out both the attacker and the user, who simply logs in again. This reuse detection makes refresh tokens much safer, especially in browsers and on mobile.
JWT structure#
A JSON Web Token (RFC 7519) is a compact, URL-safe string of three Base64url-encoded parts separated by dots: header.payload.signature.
- Header: metadata, such as the signing algorithm (
alg, for exampleRS256orES256), the token type, and a key ID (kid) that names the verification key. - Payload: the claims. Registered claims include
iss(issuer),sub(subject, the user ID),aud(audience, the service the token is for),exp(expiry),iat(issued at),nbf(not before) andjti(a unique token ID). Applications add their own claims, such as roles, tenant or scopes. - Signature: computed over the encoded header and payload, with the issuer's key. For HMAC (HS256) it is a shared secret. For RS256 or ES256 it is an RSA or ECDSA private key, verified with the matching public key.
{ "alg": "ES256", "typ": "JWT", "kid": "2026-11-key-a" }
.
{ "iss": "https://auth.example.com", "sub": "user_123", "aud": "orders-api",
"exp": 1767226500, "iat": 1767225600, "scope": "orders:read", "tenant": "acme" }
.
<ECDSA signature over base64url(header) + "." + base64url(payload)>To verify a JWT, the receiver decodes the header, picks the key named by kid from the issuer's published key set (a JWKS, JSON Web Key Set, usually at a well-known URL and cached), and checks the signature. It then validates iss, aud, exp and nbf, allowing for clock skew of up to about 60 seconds. Only after all those checks may it trust the claims.
Signed is not encrypted. A standard JWT is a JWS (JSON Web Signature): anyone holding it can decode and read the payload. Base64url is encoding, not encryption. Never put secrets or sensitive personal data in a JWT. If the claims must be confidential, use JWE (JSON Web Encryption), or better, use an opaque token and keep the data server-side.
Prefer asymmetric signatures (ES256, EdDSA, RS256) in distributed systems. Only the issuer holds the private key, and every service verifies with the public key. With HS256, every verifier holds the shared secret, and so every verifier could also mint tokens.
JWT pitfalls, in depth#
JWTs are easy to use and easy to misuse. These are the classic mistakes.
- Accepting
alg: none. Early libraries accepted tokens with an "unsigned" algorithm, so an attacker could forge any token. Always pin the expected algorithms on the verifier side, and never trust the token's ownalgheader to choose the verification method. - Algorithm confusion (RS256 → HS256). If the verifier accepts both, an attacker can sign a token with HS256, using the issuer's public key as the HMAC secret. A naive library then verifies it with that public key, and accepts it. Pin the algorithm per key.
- Not validating
audandiss. A token issued for service A (aud = A) is replayed against service B, which accepts any valid signature from the IdP. Every service must check that the audience is itself. - Missing or very long expiry. A stolen token with no
exp, or a 30-dayexp, is a long-lived skeleton key. Keep access tokens short-lived (minutes), and use refresh tokens for longevity. - No revocation plan. "Stateless" tokens can't be logged out. Choose a strategy from the list above (short TTL with refresh, a denylist, a valid-after time, or introspection), and accept a small amount of state.
- Trusting stale claims. A token issued with
role: adminkeeps saying admin for its lifetime, even after the user is demoted. Keep authorization-critical claims minimal, keep lifetimes short, or check current permissions server-side for sensitive actions. - Header injection through
kid,jkuorx5u. Libraries that fetch keys from a URL in the token, or usekidin file paths or SQL queries, can be tricked into using an attacker's key. Resolvekidonly against a fixed, trusted key set. - Sensitive data in the payload. Anyone can read it. See above.
- Huge tokens. Embedding every permission produces multi-kilobyte tokens on every request. Some proxies reject headers over 8 KB, and mobile bandwidth suffers. Put coarse claims in the token, and look up fine-grained permissions.
- Using JWTs as sessions in a single monolith with a browser front end. That gains nothing over a session cookie, and loses revocation. JWTs earn their cost when many independent services must verify identity without a shared session store.
Key rotation. Publish keys through JWKS, each with a kid. To rotate, add the new key to the JWKS, wait for caches to pick it up (hours), start signing with the new key, and remove the old key after the longest token lifetime has passed. Verifiers that see an unknown kid should refresh the JWKS, rate-limited so attackers can't force constant refreshes.
Alternatives. PASETO (Platform-Agnostic Security Tokens) was designed to avoid JWT's algorithm agility. Each version fixes the cryptography, so there's no alg header to abuse. Opaque tokens (random strings looked up through introspection or a cache) avoid the problems of self-contained claims entirely, at the cost of a lookup. Many large systems use opaque tokens at the public edge, and convert them into short-lived internal JWTs at the gateway: the "phantom token" pattern.
OAuth 2.0 flows#
Before OAuth, a printing website that wanted your photos from a photo-hosting site would ask for your photo-site password. That gave it full access to your account, forever, until you changed your password. OAuth 2.0 (RFC 6749, 2012) replaced this with delegated, scoped access. You approve a specific access at the photo site ("read photos for the next hour"), and the printing site receives a token for exactly that. It never sees your password.
OAuth defines four roles.
- Resource owner: the user who owns the data.
- Client: the application that wants access, such as the printing site or a mobile app.
- Authorization server: issues tokens after authenticating the user and getting consent. Examples are Google's OAuth server, Okta, Auth0 and Keycloak.
- Resource server: the API holding the data, which accepts tokens.
The main flows (grant types) are these.
- Authorization code with PKCE. This is the standard flow for apps acting on behalf of a user: web apps, single-page apps and mobile apps. The client sends the user's browser to the authorization server. The user logs in and approves. The browser is redirected back with a short-lived authorization code, and the client exchanges that code for tokens over a direct back-channel call. PKCE (Proof Key for Code Exchange, RFC 7636, pronounced "pixy") proves that the client exchanging the code is the same client that started the flow. That stops an attacker who intercepts the code from using it. It was designed for mobile and public clients, and is now recommended for all clients.
- Client credentials. This is for machine-to-machine calls with no user, such as a backend job calling an API. The client authenticates with its own credentials (a client secret, or better, a private-key JWT or mTLS) and receives a token for its own identity.
- Device authorization (RFC 8628). This is for devices with limited input, such as TVs and command-line tools. The device shows a short code and a URL. The user approves on their phone or laptop, while the device polls the authorization server until the token is issued.
- Refresh token. Exchange a long-lived refresh token for a new access token, without involving the user.
Two older flows are deprecated. The implicit flow returned tokens directly in the redirect URL, where they leaked through browser history and referrer headers. The resource owner password credentials flow had the app collect the user's password, which defeats the purpose of OAuth. The OAuth 2.0 Security Best Current Practice (RFC 9700, 2025) and the OAuth 2.1 draft remove both, and require PKCE for authorization code flows.
The authorization code flow with PKCE, step by step:
Before the redirect, the client generates a random code_verifier (43–128 characters), and sends its SHA-256 hash as the code_challenge. Only the client knows the verifier. When the client later exchanges the code, the authorization server hashes the verifier, and checks that it matches. An attacker who steals the code, for example through a malicious app registered for the same custom URL scheme on a phone, can't produce the verifier.
The state parameter, a random value checked on return, protects against CSRF on the redirect. Exact redirect URI matching keeps codes from being sent to attacker-controlled URLs.
OAuth, in depth: scopes, token types and the surrounding standards#
Scopes name the access requested, such as photos:read, calendar.events or repo. The user consents to scopes, the authorization server records them in the token, and the resource server enforces them. Scopes describe what the client may do on the user's behalf. They aren't the user's own permissions. A token with scope orders:write still only lets the client modify orders this user may modify. Resource servers must check both the scope and the user's own authorization.
Access tokens and refresh tokens.
- Access tokens are short-lived, typically 5–60 minutes. They are sent to resource servers, and they may be JWTs or opaque.
- Refresh tokens are long-lived, from days to months. They are sent only to the authorization server, and they are revocable and rotated.
That separation limits damage. A leaked access token expires soon, and a refresh token is only ever sent to one carefully protected endpoint.
Confidential and public clients. A confidential client, such as a server-side web app, can keep a secret, so it authenticates when exchanging codes. A public client, such as a mobile app or a single-page app, can't keep a secret, because anything shipped to devices can be extracted. That is why PKCE exists, and why public clients get shorter-lived tokens and stricter rotation.
Surrounding standards worth knowing.
- Token introspection (RFC 7662): resource servers ask whether an opaque token is active, and what its scopes and subject are.
- Token revocation (RFC 7009): clients revoke tokens at logout.
- JWT access tokens (RFC 9068): a standard profile for access tokens issued as JWTs.
- Token exchange (RFC 8693): swap one token for another, such as a user's token for a narrower token aimed at a downstream service, preserving the user's identity through a chain of calls.
- Proof-of-possession: DPoP (RFC 9449) and mTLS-bound tokens (RFC 8705) tie a token to a key held by the client. A stolen token is then useless without that key. This addresses the "bearer" weakness, where whoever holds a bearer token can use it.
- Pushed authorization requests (PAR, RFC 9126): the client sends the authorization parameters directly to the server, and gets back a reference to use in the redirect. Request parameters then can't be tampered with in the browser.
OAuth is authorization, not authentication. An access token says "this client may access these APIs for someone". On its own, it doesn't tell the client reliably who the user is. Apps that "logged users in with OAuth" by calling a profile API with an access token were vulnerable to token substitution, where a token obtained by another app for the same user was accepted. OpenID Connect fixes this.
OpenID Connect and SSO#
OpenID Connect (OIDC), from the OpenID Foundation in 2014, is an identity layer on top of OAuth 2.0. When a client requests the openid scope in an authorization code flow, the authorization server, now acting as an OpenID Provider, returns an ID token alongside the access token. The ID token is a signed JWT addressed to the client (its aud is the client ID). It states who the user is (sub, plus optional email and name), who authenticated them (iss), when (auth_time), how (amr, acr), and it carries a nonce that the client sent, to prevent replay. The client verifies the ID token, and logs the user in.
OIDC also standardises:
- a UserInfo endpoint, for profile claims;
- discovery: a
/.well-known/openid-configurationdocument listing the endpoints and the JWKS URL; - dynamic client registration;
- logout mechanisms.
"Sign in with Google", "Sign in with Apple" and "Sign in with Microsoft" are all OIDC.
Single sign-on (SSO) lets a user authenticate once with an identity provider, and then use many applications without logging in again. The pattern works like this.
- The user opens app A, which has no session for them, so it redirects them to the IdP.
- The IdP has no session either, so the user logs in. The IdP sets its own session cookie, and redirects back to A with an authorization code. A exchanges the code for an ID token, and creates its own local session.
- Later, the user opens app B, which redirects to the IdP. The IdP sees its existing session cookie, so it skips the login, and immediately redirects back to B with a code. B creates its own session. The user never typed a password for B.
SSO, in depth: SAML, federation, provisioning and logout#
SAML 2.0 (OASIS, 2005) is the older enterprise SSO standard. Signed XML assertions are posted through the browser from an identity provider to a service provider. SAML remains everywhere in enterprise software. Many B2B products must support both SAML and OIDC, because their customers' IdPs (Okta, Microsoft Entra ID, Ping, Google Workspace) speak both. Design-wise they are equivalent: redirect to the IdP, receive a signed statement about the user, create a local session. SAML's XML signatures have a history of subtle verification bugs (XML signature wrapping), so use well-maintained libraries.
Federation in B2B products. In a multi-tenant SaaS product, each customer organisation may bring its own IdP. The login flow must:
- discover which IdP to use, typically from the email domain or a tenant-specific login URL;
- map the IdP's user identifier to a local account;
- enforce the organisation's policy, such as "users of acme.com must log in through Acme's SSO, and never with a password".
Store a stable identifier, the (issuer, sub) pair, rather than the email address. Email addresses change, and they can be reassigned.
Provisioning with SCIM (System for Cross-domain Identity Management, RFC 7644). SSO handles login. Provisioning handles the lifecycle: creating accounts when employees join, updating their attributes and groups, and, critically, deactivating them when they leave. Without SCIM, a departed employee's account in your app may stay active, even though their IdP account is disabled, and their app session may outlive their employment.
Logout is hard in SSO. Logging out of app A ends A's session, but the IdP session and app B's session remain. The options are:
- RP-initiated logout: the app redirects to the IdP's logout endpoint;
- front-channel logout: the IdP loads each app's logout URL in hidden frames, which third-party cookie restrictions increasingly break;
- back-channel logout: the IdP calls each app's logout endpoint server-to-server, with a signed logout token. This is the most reliable.
In practice, keep application sessions reasonably short. Re-check with the IdP silently, by redirecting with prompt=none, and accept that full global logout is "best effort, soon".
API keys#
API keys are long random strings that identify and authenticate an application or integration, not a human. A developer creates a key in a dashboard, stores it in their server's configuration, and sends it with each request:
GET /v1/events
Authorization: Bearer sk_live_51Hx…redactedThe server looks up the key, identifies the account and its permissions and rate limits, and handles the request. API keys suit:
- server-to-server calls with third-party developers (payment APIs, messaging APIs, maps);
- simple internal integrations, where you control both sides.
They are simple to understand, easy to use from curl, and they map cleanly to billing and rate limiting (Rate Limiting and Throttling).
API keys are a poor fit for end users. People shouldn't manage long random strings. Keys don't carry user context or expire on their own, and a key embedded in a mobile app or a web page is effectively public. For user-facing apps, use sessions or OAuth tokens. For browser-side integrations, use publishable keys with very limited power. Stripe's pk_ publishable keys, for example, can only create tokens, unlike its secret sk_ keys.
API keys, in depth: generation, storage, scoping and rotation#
Generate keys with enough entropy. Use at least 128 bits from a cryptographically secure random generator, encoded in Base62 or Base64url. Add a recognisable prefix (sk_live_, ghp_, xoxb-) and, optionally, a checksum. Prefixes help humans tell key types apart. They also let secret scanners find leaked keys automatically in code repositories, logs and pastes. GitHub's secret scanning partner programme notifies providers when tokens with their formats are pushed to public repositories, so the providers can revoke them.
Store only a hash. Treat API keys like passwords. Store a hash of the key, not the key. Because keys are high-entropy random values, a fast hash such as SHA-256 (or an HMAC with a server-side pepper) is sufficient. Slow password hashes aren't needed, as the key can't be guessed by brute force. Show the full key once at creation, and afterwards only its prefix and last four characters. Look up the key by its hash, with an index on the hash column, and cache the result briefly at the gateway.
Scope keys narrowly. Support restricted keys, limited to specific resources, read-only operations, environments (test or live), IP ranges, or expiry dates. A key used by a reporting job should not be able to issue refunds.
Rotate without downtime. Allow two active keys per integration. The customer creates a new key, deploys it, verifies it, then revokes the old key. Log each key's last-used time, so dormant keys can be found and revoked. Keys that are unused for 90 days are prime candidates.
Request signing as a stronger alternative. A bearer API key in a header can be replayed by anyone who intercepts it. HMAC request signing keeps the secret on the client, and sends a signature over the request: method, path, a hash of the body, a timestamp. The server recomputes the signature and checks it, and rejects stale timestamps, limiting replay to a window of a few minutes. AWS Signature Version 4 is the best-known example. Webhooks reverse the direction. Providers sign the webhook payloads they send (Stripe's Stripe-Signature header, for example), so receivers can verify the sender, and reject replays.
mTLS between services#
Inside a microservice architecture, services call each other constantly. How does the payment service know that a request really comes from the order service, and not from a compromised container somewhere else in the network? The old answer was "it's inside our network, so trust it". A single foothold then exposes everything. The modern answer is zero trust: every service authenticates every call, regardless of network location.
Mutual TLS (mTLS) is the standard tool. In ordinary TLS, only the server presents a certificate, and the client verifies it. In mTLS, both sides present certificates, and verify each other.
- Each service instance gets a certificate that encodes its service identity. In SPIFFE form that is a URI such as
spiffe://prod.example.com/ns/payments/sa/payment-api, signed by an internal certificate authority. - When the order service calls the payment service, the TLS handshake proves both identities cryptographically, and encrypts the traffic.
- The payment service then applies service-level authorization: "only
ordersandrefundsmay callPOST /charges".
Managing certificates by hand for thousands of short-lived containers is impractical, so service meshes automate it. Istio and Linkerd inject a sidecar proxy, or use a node-level proxy, next to each workload. The mesh issues short-lived certificates, typically valid for hours, rotates them automatically, and enforces mTLS and authorization policies, all without application code changes. SPIFFE (Secure Production Identity Framework for Everyone) standardises the identity format, and SPIRE implements identity issuance by attesting workloads: proving that a process really is a given Kubernetes service account on a given node.
Service identity, in depth: propagating end-user identity and zero trust#
mTLS authenticates the calling service, but most authorization decisions also need the end user: "the order service may call payments, for orders belonging to the requesting user". Identity must be propagated along the chain of calls.
- Forward the user's access token. Downstream services re-verify the token. This is simple, but a token whose audience is the gateway is then accepted by internal services, which widens the blast radius if it leaks. Audiences become a mess.
- Mint internal tokens at the edge. The gateway verifies the external credential (a session, an OAuth token or an API key), and issues a short-lived internal JWT, valid for a minute or so, with the user, tenant, scopes and a request ID. Internal services trust only internal tokens, signed by an internal key. This is the phantom-token or "passport" pattern. Netflix has described a similar approach, which it calls "Passport", for propagating user identity internally.
- Token exchange (RFC 8693). Each hop exchanges the token for a narrower token aimed at the next service. This gives the strongest least-privilege property, and costs the most.
The combination of mTLS (which service is calling) and a propagated user context (on whose behalf) lets each service make complete authorization decisions. It also defends against the confused deputy problem, where a privileged service is tricked into using its own authority on behalf of a caller who lacks it. A file-conversion service with read access to all buckets, asked to "convert" another tenant's file, is a classic example. The defence is to authorize against the original caller's permissions, not only the deputy's.
Zero trust beyond services. Google's BeyondCorp papers (starting with Ward and Beyer, ";login:", 2014) described moving employee access from the network perimeter, via VPNs, to per-request decisions based on user and device identity and state, enforced by an access proxy. The same principles apply everywhere:
- authenticate every request;
- authorize based on identity and context, not network location;
- encrypt everywhere;
- grant least privilege;
- keep credentials short-lived.
Passkeys and WebAuthn#
Passwords fail in predictable ways: they are reused, phished, leaked in breaches, and guessed. Passkeys replace them with public-key cryptography, built on the W3C WebAuthn API and the FIDO Alliance's CTAP protocol (together called FIDO2).
Registration.
- The website sends a random challenge.
- The user's device (phone, laptop or security key) creates a new key pair specific to that website.
- The device keeps the private key, protected by the device's secure hardware and unlocked by biometrics or a PIN.
- The device sends the public key to the website, which stores it against the user's account.
Login.
- The website sends a new challenge.
- The device asks the user to unlock (fingerprint, face, PIN), and signs the challenge with the private key.
- The website verifies the signature with the stored public key.
No shared secret ever crosses the network, and the server stores only public keys. A breach of the server's database reveals nothing an attacker can log in with.
Why passkeys resist phishing. The browser includes the website's origin in the data that is signed, and the authenticator only uses credentials registered for that relying party ID. A fake site at examp1e.com can't ask for a signature valid for example.com. The browser won't let it, and the credential doesn't exist for that domain. A user can't be tricked into handing over a passkey, the way they can be tricked into typing a password or an OTP code.
Passkeys, in depth: synced vs device-bound, attestation and recovery#
Synced passkeys and device-bound keys.
- Device-bound credentials live in one hardware authenticator, such as a YubiKey or a platform authenticator with no sync. They are very strong, but losing the device loses the credential.
- Synced passkeys are backed up and synchronised by the platform's credential manager: iCloud Keychain, Google Password Manager, 1Password and others. They survive device loss and work across a user's devices. In May 2022, Apple, Google and Microsoft jointly announced their commitment to expanding support for FIDO-based passwordless sign-in, which led to synced passkeys across their platforms.
Synced passkeys trade a little assurance, since the private key now exists in a cloud-synced vault, for much better usability and recovery. For most consumer services, that trade is clearly worth it.
Cross-device sign-in. When a passkey is on a phone and the user is at a laptop, the laptop shows a QR code. The phone scans it, and the two communicate over Bluetooth proximity plus an encrypted relay (the "hybrid" transport). The proximity requirement prevents remote phishing.
Attestation. During registration, an authenticator can provide an attestation: a statement signed by the manufacturer that describes the authenticator model. High-assurance environments, such as government or regulated enterprises, use it to allow only certified hardware keys. Consumer services usually don't request attestation, because it adds friction and privacy concerns for little benefit.
Server-side design.
- Store credentials as
(credential_id, user_id, public_key, sign_count, transports, created_at, last_used), and allow several per user. - Verify the challenge, origin, relying party ID hash, flags (user presence, user verification) and signature on every login.
- Track signature counters where authenticators provide them. A counter that goes backwards can indicate a cloned authenticator. Synced passkeys often report 0, so treat counters as a signal, not a rule.
- Use discoverable credentials for username-less sign-in ("Sign in with a passkey" with no username field).
- Use conditional UI (passkey autofill) to offer passkeys alongside existing login fields.
Recovery and migration. Passkey security is only as good as the recovery path. If "lost your passkey?" falls back to an SMS code, attackers will target that path. Strong recovery uses another registered passkey, a recovery code generated at enrolment, or identity verification with a delay and notifications. Most services adopt passkeys gradually: offer creation after a password login, encourage several passkeys per account, and eventually let users remove their password.
Authorization models: RBAC, ABAC and ReBAC#
Once you know who the caller is, you need a model for deciding what they may do. The models form a progression, and most real systems combine them.
Access control lists (ACLs). Each resource holds a list of who may do what: "document 42: Alice read and write, Bob read". ACLs are simple and precise. They become hard to manage when there are thousands of users, and they make questions like "what can Alice access?" expensive to answer.
Role-based access control (RBAC). Permissions are grouped into roles, and users are assigned roles. Users get permissions only through roles. In a ticketing system, for example:
customer: book tickets; view and cancel own bookings.venue_manager: create events; view sales for their venues.support_agent: view any booking; issue refunds up to $100.admin: everything, with an audit trail.
RBAC is easy to understand, audit and explain ("why can Bob do this? because he's a support agent"), and it covers most business applications. Its weaknesses appear with context.
- "Own bookings" and "their venues" aren't roles. They're relationships, or attributes, between the user and the resource.
- Teams invent ever more specific roles to capture exceptions ("support-agent-EU-refunds-under-500"). This is role explosion.
Roles are usually scoped to a tenant or project: Alice is admin in organisation Acme, not globally. That one step, roles on a scope, already captures a lot of real-world structure.
Attribute-based access control (ABAC). Decisions come from policies evaluated over attributes of the subject (department, clearance, region), the resource (owner, classification, tenant), the action, and the environment (time, IP address, device health). For example: "allow refund if subject.role = support_agent AND resource.amount ≤ 100 AND subject.region = resource.region". ABAC is very expressive, and avoids role explosion. The costs are that policies can become hard to understand, and decisions need attribute data at check time. "Who can access X?" is also hard to answer, because access is computed, not stored. AWS IAM policies with conditions are ABAC-style.
Relationship-based access control (ReBAC). Access derives from relationships in a graph.
- Alice is an editor of folder F.
- Document D is in folder F.
- Editors of a folder are editors of the documents in it.
- Editors are also viewers.
- So Alice can view D.
ReBAC naturally models sharing, hierarchies, groups and organisations, which is what collaborative products need: Google Drive, GitHub repositories and teams, Notion workspaces. It was popularised by Google's Zanzibar system.
| Model | Decision based on | Strengths | Weaknesses | Fits |
|---|---|---|---|---|
| ACL | Per-resource lists | Simple, precise | Hard to manage at scale; reverse queries expensive | Small systems; file permissions |
| RBAC | Roles assigned to users (often per tenant) | Easy to audit and explain | Role explosion; poor at ownership and context | Business apps, admin consoles |
| ABAC | Policies over attributes | Very expressive; context-aware | Policies hard to reason about; attribute plumbing | Regulated data, cloud IAM, conditional access |
| ReBAC | Relationships in a graph | Natural for sharing and hierarchy; can answer "who can see X" | Needs a graph store and careful consistency | Collaboration products, multi-level orgs |
Authorization at scale, in depth: Zanzibar and policy engines#
Google Zanzibar. The paper "Zanzibar: Google's Consistent, Global Authorization System" (Pang et al., USENIX ATC 2019) describes the system behind permissions for Google Drive, YouTube, Calendar, Cloud and other products. The paper reports trillions of access control entries, millions of authorization checks per second, and p95 latency under 10 ms.
- Data model: relation tuples of the form
object#relation@user, such asdoc:roadmap#viewer@user:bob. The user can also be a userset, such asdoc:roadmap#editor@group:eng#member, meaning "members of group eng are editors". - Namespace configuration defines each object type's relations, and userset rewrite rules that derive one relation from another. For example: "viewer includes editor", and "editor includes the parent folder's editor". This keeps the number of tuples small. You store "Alice is editor of folder F" once, and the rules derive access to every document inside it.
- APIs: Check ("does user U have relation R on object O?"), Read, Write, Expand (show the tree of who has access), and Watch (a stream of tuple changes, used to build secondary indexes).
- Consistency: the "new enemy" problem. Suppose Alice removes Bob from a document, then adds confidential content. If a stale replica evaluates Bob's check against the old ACL but the new content, Bob sees what he shouldn't. Zanzibar solves this with zookies: opaque consistency tokens that encode a timestamp. When content is modified, the client stores the zookie returned by a content-change ACL check. Later checks carry the zookie, and Zanzibar evaluates them at a snapshot at least as fresh as that time. It builds on Spanner's externally consistent timestamps. Most checks can use slightly stale snapshots, which are fast and cacheable, while ordering-sensitive checks get the freshness they need.
- Performance: aggressive caching of intermediate check results, request hedging, deduplication of concurrent identical checks, and a specialised index service (Leopard) for flattening deeply nested group memberships.
Open-source systems inspired by Zanzibar include SpiceDB (AuthZed), OpenFGA (originally from Auth0/Okta, now a CNCF project), Ory Keto and Permify. They let ordinary teams adopt ReBAC without building a global consistency system. They expose the same Check, Write and Expand style APIs, and similar schema languages.
Policy engines. Some systems express authorization as code-like policies, evaluated by a general engine.
- Open Policy Agent (OPA) is a CNCF graduated project. Policies are written in Rego, and OPA is used for Kubernetes admission control, API authorization and infrastructure policy.
- Cedar is AWS's open-source policy language (2023), designed to be analysable. Its semantics were built for automated reasoning, so tools can prove properties such as "no policy grants public access". It powers Amazon Verified Permissions.
Policy engines shine for ABAC-style rules, and for centralising policy across many services. ReBAC systems shine when the data is the permission: shares, memberships and hierarchies. Hybrids are common, such as a ReBAC graph for relationships plus policy conditions for context.
The reverse question: list filtering. "Can Alice see document D?" is one check. "Show Alice the 20 newest documents she can see" is harder. Checking every document one by one doesn't scale to millions of documents. Strategies:
- Pre-filter in the query: maintain an index of accessible resource IDs, or group IDs, per user, and join against it. This is easy with simple RBAC or tenant scoping, such as
WHERE tenant_id = ?. - Post-filter with batched checks: fetch candidates, check them in batches, and keep fetching until the page is full. This works when most candidates are visible.
- Materialised permission indexes: Zanzibar-style systems offer a LookupResources API, or a Watch stream, to keep a denormalised "who can see what" index in the search engine. Search queries can then filter by ACL tokens stored on each document.
Designing a permission system#
A practical design brings these ideas together. Consider a document-collaboration product with organisations, teams, folders and documents, where users share documents with each other.
1. Separate the parts (the XACML vocabulary is useful here).
- Policy Enforcement Point (PEP): the code that asks "is this allowed?" and enforces the answer. That is the gateway for coarse checks, and each service for fine checks.
- Policy Decision Point (PDP): computes the decision. It could be a library, a sidecar such as OPA, or a service such as SpiceDB or OpenFGA.
- Policy Administration Point (PAP): where policies and roles are managed: admin consoles, share dialogs, policy repositories.
- Policy Information Point (PIP): supplies the attributes and relationships that decisions need.
2. Define the model explicitly. Write the schema:
- object types (organisation, team, folder, document);
- relations (owner, editor, commenter, viewer, member, parent);
- derivation rules (owner ⇒ editor ⇒ commenter ⇒ viewer; folder editors are document editors; organisation admins are owners of everything in the organisation).
Then map each API endpoint to the permission it requires: GET /docs/:id requires viewer, PATCH requires editor, POST /docs/:id/share requires owner, or editor if the organisation allows editors to share.
3. Enforce at the right layers.
- The gateway checks authentication, token validity, coarse scopes and tenant membership. It cheaply rejects requests that are obviously unauthorized.
- Services perform object-level checks next to the data, on every request, including the internal and batch paths.
- The data layer enforces tenant isolation as defence in depth. That might be PostgreSQL row-level security keyed on the tenant, or separate schemas or databases for large tenants.
4. Deny by default. Every endpoint requires an explicit permission. Make "no rule matched" mean deny. Write a test that fails if a new route has no declared permission.
5. Handle performance. Checks are on the hot path.
- Cache decisions briefly: seconds, keyed by subject, relation and object, plus a consistency token where it matters.
- Batch checks for list pages.
- Precompute group memberships.
- Keep the PDP close to services: a sidecar, or a same-zone cluster.
A reasonable target is p99 under 10 ms per check, and a few checks per request.
6. Handle consistency deliberately. Most checks can tolerate a few seconds of staleness. Revocations and "new enemy" orderings can't. Either use consistency tokens (Zanzibar-style), or force fresh checks after permission changes on that object.
7. Audit everything important. Log permission changes (who granted what to whom, and when), and decisions on sensitive actions (exports, admin actions, access to confidential data), with the request ID. Many compliance regimes, such as SOC 2 and HIPAA, expect audit trails. Audits also answer the inevitable "who shared this?"
8. Plan for special cases:
- break-glass access for support, which is time-limited, justified, and logged with an alert;
- impersonation ("view as user") that is visible and logged;
- service accounts with least privilege;
- public links, which are capability URLs with unguessable tokens and expiry;
- ownership transfer when users leave an organisation.
Permission systems, in depth: multi-tenancy, sharing and failure modes#
Tenant isolation first. In B2B SaaS, the worst authorization bug is a cross-tenant leak, where one customer sees another's data. Defences, from cheapest to strongest:
- every query filters on
tenant_idtaken from the authenticated context, never from request parameters; - row-level security in the database, enforcing the tenant filter even if application code forgets it;
- per-tenant encryption keys;
- separate databases or cells for large or regulated tenants.
Combine at least two layers.
Insecure direct object references (IDOR or BOLA). These are the most common API authorization bug: GET /invoices/1001 works for anyone who guesses the ID, because the code checks authentication but not ownership. Unguessable IDs such as UUIDs reduce casual discovery, but they aren't access control. Always check the relationship between the caller and the object.
Sharing semantics are product decisions.
- Can editors re-share? Can external users be invited?
- Do link shares require sign-in? Do shares expire?
- What happens to shared documents when the owner leaves the organisation?
Encode the answers in the schema, not in scattered if statements.
What happens when the PDP is down? Authorization should almost always fail closed. Denying access is safer than granting it. To keep availability high:
- run the PDP replicated across zones;
- cache recent positive decisions for a short time, such as 30–60 s, so brief outages are invisible for active users;
- design degraded modes explicitly: for example, read-only access for owners, from a local cache.
This differs from rate limiting, where failing open is often acceptable. A permission system that fails open is a data breach.
Testing authorization.
- Unit-test the policy or schema with tables of (subject, action, resource → expected).
- Run automated cross-tenant and cross-user tests against every endpoint: user A tries user B's IDs.
- Diff policies in code review.
For policy languages designed for analysis, such as Cedar, automated reasoning can verify properties of whole policy sets.
When to Use It#
- Server-side sessions with cookies: a traditional web app, or a single domain, with a browser front end. You want instant revocation and minimal client-side complexity.
- OAuth 2.0 / OIDC with short-lived JWT access tokens: many services or APIs must verify identity independently; mobile apps; third-party apps acting on behalf of users; "Sign in with…" and enterprise SSO.
- A backend-for-frontend holding tokens: single-page apps that need OAuth, but where you don't want tokens in browser JavaScript.
- API keys (with scopes, hashing and rotation): developer platforms and partner integrations, where server-to-server calls are made by an account rather than a person.
- OAuth client credentials or mTLS: machine-to-machine calls, needing standard short-lived tokens or transport-level identity.
- mTLS with a service mesh and SPIFFE identities: internal service-to-service authentication in zero-trust architectures.
- Passkeys: consumer and workforce login, where phishing resistance and lower password-support costs matter.
- RBAC (per tenant): most business apps and admin consoles.
- ABAC or a policy engine: context-heavy rules, regulatory constraints, or policy shared across many services.
- ReBAC (a Zanzibar-style service): sharing, nested groups, hierarchies, and "who can see this" questions at scale.
When NOT to Use It#
- JWTs for a single monolith's browser sessions, where you need logout to work immediately. Sessions are simpler, and revocable.
- Long-lived bearer tokens, or API keys, in browsers or mobile apps. Anything shipped to a client is extractable.
- The implicit or password grants in new OAuth deployments. Both are deprecated.
- Building your own identity provider or cryptography, unless identity is your product. Use well-maintained IdPs and libraries. The subtle bugs (signature verification, redirect handling, session fixation, timing attacks) are already fixed there.
- A Zanzibar-style system for simple role checks. A role column and a tenant filter serve most applications for years.
- Network location as authorization ("it's from inside the VPC"). A single compromised workload then reaches everything.
- SMS one-time codes as the strongest factor for high-value accounts. Prefer passkeys or hardware keys.
How to Implement It#
- Pick an identity provider. That might be a managed one (Auth0, Okta, Microsoft Entra ID, AWS Cognito, Firebase Authentication) or a self-hosted one (Keycloak, Ory, Zitadel). Use OIDC for user login, and enable MFA, ideally passkeys.
- Choose the session model per client type.
- Browser apps:
HttpOnly,Secure,SameSitesession cookies, with a BFF for single-page apps. - Mobile apps: authorization code + PKCE, with tokens in the platform's secure storage.
- Third parties: OAuth with scopes.
- Developers: scoped, hashed API keys.
- Browser apps:
- Issue short-lived access tokens (5–15 minutes) as asymmetric-signed JWTs with
iss,sub,aud,expand minimal claims. Issue rotating refresh tokens with reuse detection. Publish a JWKS, and plan key rotation. - Verify at the gateway, and again in services. The gateway authenticates and applies coarse checks. Services verify the token, or an internal token minted by the gateway, and perform object-level authorization.
- Secure service-to-service traffic with mTLS (a service mesh, SPIFFE/SPIRE), plus service-level allow lists, and propagate the end-user context in short-lived internal tokens.
- Model authorization explicitly: roles per tenant to start with; a policy engine for context rules; a ReBAC service when sharing and hierarchy dominate. Deny by default. Declare a permission for every endpoint.
- Protect the flows around login: rate-limit login, MFA and recovery endpoints; check breached passwords; use step-up authentication for sensitive actions; revoke sessions on password change.
- Audit and monitor: log authentication events (successes, failures, MFA, recovery) and permission changes. Alert on anomalies, such as impossible travel, bursts of failures, or new API keys being used from new networks.
Verifying an access token in a TypeScript service, with the jose library:
import { createRemoteJWKSet, jwtVerify, errors } from "jose";
// JWKS is fetched once and cached; unknown kid triggers a (rate-limited) refresh
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
export interface Principal { userId: string; tenant: string; scopes: Set<string> }
export async function authenticate(authHeader?: string): Promise<Principal> {
if (!authHeader?.startsWith("Bearer ")) throw new HttpError(401, "missing token");
try {
const { payload } = await jwtVerify(authHeader.slice(7), JWKS, {
issuer: "https://auth.example.com",
audience: "orders-api", // reject tokens minted for other services
algorithms: ["ES256"], // pin algorithms: no "none", no HS/RS confusion
clockTolerance: 60, // seconds of allowed skew
});
return {
userId: String(payload.sub),
tenant: String(payload.tenant),
scopes: new Set(String(payload.scope ?? "").split(" ")),
};
} catch (e) {
if (e instanceof errors.JWTExpired) throw new HttpError(401, "token expired");
throw new HttpError(401, "invalid token");
}
}
// Authorization is separate: scope check plus an object-level check near the data
export async function requireOrderAccess(p: Principal, orderId: string, action: "read" | "cancel") {
if (!p.scopes.has(action === "read" ? "orders:read" : "orders:write")) throw new HttpError(403, "scope");
const order = await db.orders.findOne({ id: orderId, tenant: p.tenant }); // tenant from token, not request
if (!order || (order.userId !== p.userId && !(await authz.check(p.userId, "support", p.tenant))))
throw new HttpError(404, "not found"); // hide existence
return order;
}| Technology | Fits when |
|---|---|
| Auth0, Okta, Microsoft Entra ID, Ping | Managed identity with OIDC/SAML, MFA, passkeys, enterprise federation and SCIM; B2B or workforce SSO |
| AWS Cognito, Firebase Authentication, Supabase Auth | App-centric user pools tightly integrated with one cloud or platform |
| Keycloak, Ory (Kratos, Hydra), Zitadel, Authentik | Self-hosted, open-source identity and OAuth/OIDC servers |
| Passkey and WebAuthn libraries (SimpleWebAuthn, webauthn4j, py_webauthn) | Adding passkeys to your own login |
| SpiceDB, OpenFGA, Ory Keto, Permify | Zanzibar-style ReBAC: sharing, hierarchy, "who can see X" |
| Open Policy Agent (Rego) | General policy engine: API authorization, Kubernetes admission, infrastructure policy |
| Cedar / Amazon Verified Permissions | Analysable policy language for application authorization; managed on AWS |
| Casbin, Oso, CASL | In-process authorization libraries for RBAC/ABAC in application code |
| Istio, Linkerd, SPIFFE/SPIRE | Automatic mTLS, workload identity and service-level authorization policies |
| HashiCorp Vault, AWS KMS / Secrets Manager | Storing signing keys and client secrets; issuing short-lived credentials |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Server-side sessions | Instant revocation; small cookie; simple | Lookup per request; shared store must be HA | Browser apps on one domain |
| Self-contained JWTs | Stateless verification; works across services | Hard revocation; stale claims; size | Many services; mobile and API clients |
| Opaque tokens with introspection | Instant revocation; no claim leakage | Lookup (cacheable) per request | Public edge; high-security APIs |
| API keys | Simple for developers; map to billing and limits | Long-lived bearer secrets; leak-prone | Server-to-server developer APIs |
| HMAC request signing | Secret never sent; replay window limited | More client complexity | High-value APIs; webhooks |
| mTLS | Strong, transport-level service identity | Certificate lifecycle (needs automation) | Internal zero-trust networks |
| Passkeys | Phishing-resistant; no shared secret | Recovery and cross-device UX need care | Consumer and workforce login |
| RBAC | Simple, auditable | Role explosion; no ownership semantics | Most business apps |
| ABAC / policy engine | Expressive, context-aware | Harder to reason about; attribute plumbing | Regulated or context-heavy rules |
| ReBAC (Zanzibar-style) | Natural sharing and hierarchy; reverse queries | Extra service; consistency design | Collaboration and multi-level orgs |
Common Pitfalls#
- Checking authentication but not object ownership. This is the IDOR/BOLA bug, and the top API security risk.
- Taking the tenant or user ID from request parameters instead of from the verified credential.
- Accepting any JWT signed by the IdP, without checking
aud, or letting the token'salgheader choose the verification algorithm. - Long-lived access tokens with no revocation plan, or with authorization-critical claims that go stale.
- Storing tokens in
localStorage, where any XSS exfiltrates them. - Missing
SameSite,HttpOnlyorSecureflags on session cookies, and not rotating the session ID at login. - Storing API keys in plaintext, or showing them again after creation. Keys committed to repositories should be detected by secret scanning and revoked.
- Redirect URI wildcards, or a missing
stateparameter, in OAuth. - Weak recovery flows that bypass strong MFA.
- Treating network location as trust inside the data centre.
- Authorization logic scattered across controllers, with no central model, so nobody can say who can access what.
- Failing open when the authorization service is unavailable.
- Not deprovisioning: departed employees keep active sessions, API keys and service accounts.
Real-World Examples#
- Google Zanzibar. Described in the 2019 USENIX ATC paper, Zanzibar stores relationship tuples for many Google products, and answers authorization checks with low latency at global scale. It uses Spanner snapshots and zookies to avoid the new-enemy problem. It inspired SpiceDB, OpenFGA and others.
- Google BeyondCorp. Google's series of papers, from 2014 onwards, described replacing VPN-based perimeter trust with per-request access decisions based on user and device identity, the foundation of the "zero trust" movement.
- Passkeys. In May 2022, Apple, Google and Microsoft announced expanded support for the FIDO passwordless standard, which led to synced passkeys in their platforms. Many large consumer services have since added passkey sign-in.
- Stripe API keys. Stripe distinguishes secret keys (
sk_live_…), publishable keys (pk_live_…) for client-side use with limited power, and restricted keys with granular permissions. It also separates test-mode and live-mode keys. - GitHub secret scanning. GitHub scans pushes for known credential formats, and notifies participating providers, which can revoke leaked tokens. GitHub's own token formats carry identifiable prefixes (
ghp_,gho_,ghs_), partly to make scanning reliable. - Netflix edge authentication. Netflix's engineering blog has described moving token handling to the edge, and propagating a "Passport" identity structure to internal services, rather than having every service process external tokens.
Case studies that use this pattern#
- Design a Collaborative Editor (Google Docs): document sharing with owner, editor, commenter and viewer roles, and link sharing. A ReBAC model.
- Design File Storage and Sync (Dropbox / Google Drive): folder hierarchy permissions, shared links, and signed URLs for downloads.
- Design a Payment System: API keys, request signing, webhooks with signatures, and strict service-to-service authentication.
- Design a Chat System (WhatsApp): device authentication, token-authenticated WebSocket connections, and per-conversation membership checks.
In the Interview#
Deep Dive: running authentication infrastructure at scaleShow
Verification cost and placement. Verifying an ES256 or EdDSA signature takes on the order of tens of microseconds of CPU, and RSA-2048 verification is similar or faster. Signing RSA is much slower, around a millisecond. At 200,000 requests a second, verification costs a few CPU cores across a gateway fleet, which is trivial. The expensive part is key distribution and failure handling.
- Cache the JWKS in memory, refreshing every few minutes and on an unknown
kid. - Prefetch keys during rotation.
- Never fetch keys on the request path without a cache, or an IdP blip becomes a fleet-wide outage.
The IdP is a tier-0 dependency. If logins fail, new sessions can't start. If token refresh fails, active users drop off as their access tokens expire. Design for it.
- Make access-token lifetimes long enough to ride out brief IdP outages: 10–15 minutes rather than 1 minute.
- Make refresh tolerant: retry with jitter, and keep using the current token until it expires.
- Run IdP infrastructure across zones and regions.
- Keep the token-verification path independent of the IdP's runtime availability, using only cached public keys.
Managed IdPs publish status pages, and have had outages. Your design should state what happens during one.
Login traffic is bursty and attacked. Login and token endpoints see morning peaks, mobile-app releases (everyone re-authenticates at once) and credential-stuffing waves that can be ten to a hundred times normal. Protect them with per-account and per-IP limits, bot detection, and progressive friction. Credential stuffing at 50,000 attempts a second against a service with 1% password reuse and no MFA would compromise hundreds of accounts per second. That is why breached-password checks, MFA and rate limits are layered.
Session and token numbers. Take 100 million users, with 30 million active per day, an average of 2 devices each, and refresh tokens rotated hourly. That gives about 60 million refresh tokens in storage (about 200 bytes each ≈ 12 GB), and roughly 60 million ÷ 3,600 ≈ 17,000 refresh operations a second at steady state, with peaks several times higher. That is a moderately sized, write-heavy key-value workload, well suited to a replicated store such as DynamoDB or Cassandra, or to sharded PostgreSQL. Reuse detection needs each refresh to atomically invalidate the old token, so it uses conditional writes.
Token theft defences beyond expiry. Bearer tokens can be stolen by malware, by malicious browser extensions, or from logs. Mitigations:
- proof-of-possession (DPoP, or mTLS-bound tokens), so a stolen token is useless without the client's private key;
- binding sessions to devices. Device-bound session credentials, which tie a browser session to a hardware-backed key, have been proposed by the Chrome team;
- anomaly detection on session use: a new country or ASN, or impossible travel, followed by step-up authentication;
- never logging
Authorizationheaders or cookies. Scrub them in proxies and application-level logs.
Deep Dive: evaluating relationship-based checks efficientlyShow
A ReBAC check is a graph reachability question: is there a path from user U to object O through relations that the schema says imply permission P? Evaluating it naively means recursive lookups: "is U a viewer of O? Viewers include editors. Is U an editor of O? Editors include the parent folder's editors. What is O's parent? Is U an editor of that folder? The folder's editors include group G's members. Is U a member of G?"
Each hop is a read of the tuple store. Deep hierarchies (folders nested 10 levels) and nested groups (groups of groups) can mean dozens of reads per check.
Techniques that make checks fast:
- Fan out in parallel and short-circuit. Evaluate the union branches (direct viewer, editor, parent's editor) concurrently, and return as soon as one succeeds. Latency then tracks the shortest successful path, not the sum of the paths.
- Cache subproblems. "Is U a member of G at snapshot T?" recurs across many checks. Zanzibar caches intermediate results keyed by snapshot, and deduplicates concurrent identical requests (a "lock table"), so a hot object doesn't cause a thundering herd on the tuple store.
- Flatten group membership. Precompute the transitive closure of group membership (user → all groups, directly or indirectly) in an index that is updated incrementally from the change stream. Zanzibar's Leopard index does this, turning deep group traversals into set intersections.
- Choose evaluation direction. Going forwards from the object (who has access to O) or backwards from the user (what U can reach) has different costs depending on fan-out. A popular document shared with a large group is cheap to check by group membership, and expensive to expand.
- Bound the depth. Schemas should limit recursion depth (for example, at most 25 levels of folder nesting), and reject cycles.
Hot spots. A tuple like "everyone in organisation Acme is a viewer of the Acme handbook", with 200,000 users, makes the handbook a hot object. Cache its result per user, and keep the group-membership index warm.
Consistency versus latency. Fresh checks must read at the latest snapshot, and can't use caches built at older snapshots. Most systems default to "minimise latency" (a recent snapshot a few seconds old). They require "at least as fresh as" tokens only for checks after a permission change, or when ordering with content matters. SpiceDB, for example, exposes consistency options that range from minimising latency to full consistency, plus "at least as fresh as" a token.
Writes. Changing permissions is rarer than checking them, typically by orders of magnitude, but writes must be durable, ordered and auditable. Each write returns a token, a revision or zookie, that callers store with the content they protect, if they need new-enemy safety.
Deep Dive: identity flow through a microservice requestShow
Follow one request through a typical architecture: a mobile app cancels a booking.
- Edge. The app sends
DELETE /bookings/987with an OAuth access token (an opaque or JWT access token, obtained earlier through authorization code + PKCE). TLS terminates at the load balancer. - Gateway.
- It verifies the token: the signature against the cached JWKS, then
iss,aud,expand the scopebookings:write. - It applies rate limits per user.
- It checks the denylist or valid-after timestamp for revoked sessions.
- It mints an internal token with a 60-second TTL:
sub,tenant,scopes,auth_time,request_id. - It strips the external token, and forwards the request.
- It verifies the token: the signature against the cached JWKS, then
- Booking service. The mesh sidecar terminates mTLS, and verifies that the caller is the gateway's SPIFFE identity. The service verifies the internal token. It loads booking 987 scoped to the tenant, and checks ownership:
booking.user_id == sub, or the caller hassupportin this tenant. If the check fails, it returns 404. - Downstream call. The booking service calls the payment service to refund. mTLS proves the caller is
booking. The internal token, or a narrower exchanged token, proves it acts for user U. The payment service authorizes on both: "booking may request refunds, for bookings whose user is U", and checks the refund amount against policy. - Audit. Both services log the decision with the request ID, the subject, the action and the resource. The payment service's log is part of the financial audit trail.
Each layer answers a different question. The gateway asks whether this is a valid, current user credential with the right scope. The mesh asks which workload is calling. The service asks whether this user may act on this object. The downstream service asks whether this workload, on behalf of this user, may do this. Removing any layer reopens a known class of attack: forged tokens, lateral movement, IDOR, or the confused deputy.
Key Takeaways#
- Authentication proves who the caller is. Authorization decides what they may do. Keep them separate, and use 401 and 403 (or 404) correctly.
- Sessions (reference credentials) give instant revocation, and suit browser apps. JWTs (value credentials) give stateless verification across services, but need short lifetimes and a revocation plan.
- A JWT is signed, not encrypted. Pin algorithms, validate
iss,audandexp, prefer asymmetric keys with a JWKS and rotation, and keep claims minimal. - OAuth 2.0 delegates scoped access. Use authorization code + PKCE for apps, client credentials for machines, and the device flow for TVs and CLIs. Implicit and password grants are deprecated.
- OpenID Connect adds ID tokens and discovery on top of OAuth. It powers social login and SSO, with SAML still common in the enterprise, and SCIM for provisioning.
- API keys suit developer server-to-server access. Use high entropy and recognisable prefixes, store only hashes, scope them, and rotate them.
- mTLS with workload identities (SPIFFE, service meshes) authenticates services. Propagate the end-user context in short-lived internal tokens, to avoid confused-deputy bugs.
- Passkeys (WebAuthn/FIDO2) are phishing-resistant and leave no server-side secrets to steal. Invest in recovery.
- Grow authorization from RBAC to ABAC policies to ReBAC (Zanzibar-style) as sharing and hierarchy demand. Deny by default, check objects near the data, fail closed, and audit.