Skip to content
Tech Interview Prep
Technical interview guide

Authentication vs. Authorization

Proving who you are versus what you're allowed to do, and the protocols behind each.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: NIST SP 800-63 Revision 4, OWASP Cheat Sheet Series, and RFC 6750 guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain authentication versus authorization with an API example.

Answer

The 90-second answer

Authentication answers "who is this caller, and can they prove it?" Authorization answers "may this proven caller do this specific thing to this specific object?" They fail differently and return different status codes: failed authentication is 401 with a WWW-Authenticate challenge; failed authorization is 403. If your API returns 403 for a missing token, you have merged the two, and clients cannot tell whether to re-login or give up.

Assume a multi-tenant API taking a JWT bearer token. A client sends Authorization: Bearer <JWT>. The gateway verifies the signature against the IdP's JWKS and checks iss, aud, exp. That is authentication: it produces a subject, sub=user_8f21. Nothing about invoices has been decided yet. Authorization is the next step: load the policy for invoices:read on tenant A's invoice 42, evaluate it against that subject, and only then touch the database.

Worked trace

Request: GET /v1/tenants/A/invoices/42

Token payload (RFC 9068 access token):

JSON
{"iss":"https://idp.example.com","sub":"user_8f21","aud":"api://billing",
 "exp":1735689600,"scope":"invoices:read"}
#ConditionResult
1No Authorization header401, WWW-Authenticate: Bearer realm="billing"
2Signature invalid or exp passed401, WWW-Authenticate: Bearer error="invalid_token"
3aud is api://reports, not api://billing401: token was not minted for this API
4Valid token, scope lacks invoices:read403
5Scope ok, sub is not a member of tenant A403 (or 404, if you don't want to leak that invoice 42 exists)

Steps 1–3 are authentication. Steps 4–5 are authorization. The tenant in step 5 comes from the verified token or a server-side membership lookup: never from the URL path alone, or you have an IDOR.

Failure modes

  • Confused deputy: service B accepts a token minted for service A and acts with B's own privileges. Prevented by aud validation; detected by alerting on aud-mismatch rejections, which should sit near zero in steady state.
  • Scope creep: one broad token reused across endpoints. Detected by logging granted scopes against required scopes per route and flagging routes where granted far exceeds required.
  • Tenant isolation break: policy checks the resource id but not the tenant. Detected by a cross-tenant test suite in CI, plus a per-tenant 403/404 ratio that spikes when a client starts guessing ids.
  • Deny-by-default cost: a new endpoint with no matching policy returns 403 in production. Detected by a policy-coverage metric (routes with a matching rule / total routes) and by canarying new routes.

Trade-offs

Sessions vs tokens: a server-side session revokes instantly but needs a shared store (Redis) or sticky routing; a JWT is stateless and scales horizontally, but revocation needs a denylist or a short TTL. Commonly 5–15 minutes plus a refresh token. Centralized policy (an OPA sidecar evaluating locally, no network hop) keeps rules consistent and auditable; per-service checks are simpler until two services disagree about who may delete an invoice. Deny-by-default is the right default, and its cost is exactly the 403-on-new-route above: pay it with coverage tests rather than by flipping to allow-by-default.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do identity proofing, authentication, federation, sessions, and authorization differ?

Answer

Five different questions get collapsed into the word "login." Proofing asks whether this is a real person and how well we know it. Authentication asks whether the subject controls a credential right now. Federation asks how one system's authentication result travels to another under trust. A session asks how we keep that result alive across requests. Authorization asks what this subject may do to this resource at this moment. They are independent: you can run AAL3 authentication on an IAL1 self-asserted account, and a perfectly authenticated user still gets a 403 on a resource they don't own.

Assumptions: a web app, an OIDC identity provider, and NIST SP 800-63 vocabulary. SP 800-63-3 (2017) defines IAL1–3, AAL1–3, FAL1–3; the 2025 revision, SP 800-63-4, keeps the same three families.

LayerQuestion it answersNIST familyTypical artefactFails as
ProofingIs this a real person, and how well do we know it?IAL1–3verified document + liveness selfiesynthetic identity, forged document
AuthenticationDoes the subject control the authenticator now?AAL1–3password, TOTP, WebAuthn assertioncredential stuffing, push bombing
FederationCan the relying party trust the IdP's result?FAL1–3signed OIDC id_token or SAML assertionassertion replay, audience confusion
SessionIs this the same subject across requests?—session cookie or refresh tokenfixation, stolen token
AuthorizationMay this subject do this to this resource?—policy decision (RBAC/ABAC/ReBAC)IDOR, broken object-level authorization

A trace makes the boundaries concrete. The user hits the relying party, which redirects to the IdP with a PKCE code_challenge (RFC 7636). The IdP authenticates (password plus TOTP, AAL2) and returns a code. The RP exchanges code plus code_verifier for an id_token (a JWT, typically RS256) and an access token, then validates iss, aud, exp and the signature against the IdP's JWKS. That validation step is federation, FAL2: a signed assertion the RP can trust. The RP then mints a session cookie (128-bit random, HttpOnly, Secure, SameSite=Lax) and that is the session layer. On a later request the cookie resolves to a subject, and authorization runs: GET /invoices/8842 passes only if the policy finds subject == invoice.owner_id, otherwise 403. Proofing happened once, at enrollment, months earlier; nothing in this trace re-checks it.

Where the design choices bite. Proofing: IAL2 remote proofing is cheap and converts well but admits more synthetic identities; IAL3 in-person with biometric costs onboarding throughput. Authentication: AAL2 software OTP is cheap but phishable; AAL3 hardware WebAuthn resists verifier impersonation but adds key distribution and recovery flows. Federation: a central IdP gives SSO and one revocation point, but a compromised IdP is a blast radius across every RP; local accounts avoid that and multiply credential stores. Session: server-side sessions revoke instantly but need a store; stateless JWTs scale but revocation needs a denylist or short TTL. Authorization: RBAC is simple until role explosion; ABAC is flexible but hard to audit; ReBAC (Zanzibar-style) is fine-grained with more moving parts.

Failure modes and how you catch them. Push bombing, attacker spams MFA prompts until the user approves, shows up as a prompt-to-approval ratio spike; rate-limit and number-match. Token replay at the wrong RP is caught by strict aud/iss checks, short exp, and sender-constrained tokens such as DPoP. Session fixation is caught by rotating the session ID on privilege change. IDOR is caught by object-level authorization tests in CI and by watching the 403/404 ratio on resource endpoints.

What would change the decision: a bank transfer needs IAL2+ proofing, AAL3, FAL3 holder-of-key assertions, short sessions, and per-transaction authorization. A read-only public dashboard needs IAL1, AAL1, FAL1, long sessions, and coarse RBAC. The layers move together only when the risk does.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Compare RBAC, ABAC, and relationship-based authorization.

Answer

The 90-second answer. These three are not interchangeable implementations of one idea; they differ in what the decision reads. RBAC reads the principal's role assignments. ABAC reads attributes of principal, resource, action and environment. ReBAC reads the graph path between principal and resource. Pick the one whose inputs you can keep accurate, then combine: roles for coarse capability, relationships for object scoping, attributes for conditions.

Mechanism. All three sit behind the same split: a PEP (the service, or a sidecar authorizer) intercepts, a PDP evaluates and returns allow/deny, a PIP supplies attributes. RBAC's PDP is set union over roles; a role is a named permission set bound to a principal. The cost is combinatorial: scope roles per (team, environment, resource class) and 40 teams × 4 environments × 6 classes = 960 roles, and every new dimension multiplies. NIST's RBAC standard (INCITS 359) adds role hierarchies and static/dynamic separation-of-duty constraints, which buy back some of it, but the role name still has to encode context.

ABAC moves context out of the name and into the request. AWS IAM is the mainstream example: "Condition": {"StringEquals": {"aws:ResourceTag/team": "${aws:PrincipalTag/team}"}} decides from tags rather than from a pre-built role. That scales in policy count, not role count, but the PDP now depends on attribute freshness, and there is no reverse index answering "who can read this object?".

ReBAC stores tuples and evaluates a graph. Zanzibar-style: doc:readme#viewer@user:alice, doc:readme#parent@folder:root. OpenFGA and SpiceDB express it as:

type folder
  relations
    define owner: [user, team#member]
    define viewer: [user, team#member] or owner
type doc
  relations
    define parent: [folder]
    define viewer: [user] or viewer from parent

Trace doc:readme#viewer@user:alice: no direct tuple → follow parent to folder:root → no direct viewer tuple → owner is team:eng#member → team:eng#member@user:alice exists → allow. Three hops, four datastore reads.

modeldecision inputenginesbreaks when
RBACrole bindingsKubernetes RBAC, NIST INCITS 359context multiplies roles; k8s RBAC is additive only, so a broad ClusterRole cannot be narrowed by a Role
ABACattributesAWS IAM tags, OPA/Rego, Cedartags go stale; no reverse index; per-request evaluation cost
ReBACgraph tuplesZanzibar, OpenFGA, SpiceDBdeep or cyclic graphs, hot tuples, stale snapshot reads

Failure modes and how you catch them. RBAC: orphaned bindings after offboarding. Diff RoleBindings against the identity provider's active set, and alert on role count growth per quarter. ABAC: a tag change the PDP's cache has not seen. Log the attribute values used in each decision so a wrong allow is reconstructible. ReBAC: the new-enemy problem, where a check reading a snapshot older than the revocation still allows. Zanzibar's answer is a zookie, a consistency token pinning the check to at least the revision of the granting write. Detect by measuring check depth and p99; a group with 100k members is a hot tuple.

Deny precedence is a property of the engine, not of the model. AWS IAM evaluates explicit Deny > Allow > implicit deny. XACML 3.0 makes it explicit with combining algorithms (deny-overrides, permit-overrides). Kubernetes RBAC has no deny rule at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain OAuth authorization code with PKCE.

Answer

PKCE (RFC 7636) closes the authorization-code interception hole for public clients (mobile apps, SPAs, CLI tools) that can't hold a client secret. The client generates a random code_verifier (43–128 characters from [A-Za-z0-9-._~]), derives a code_challenge from it, and sends the challenge on the authorization request. The authorization server stores the challenge alongside the code. At redemption the client sends the raw verifier; the server re-derives the challenge and compares. An attacker who steals the code off the redirect (a malicious app that registered the same custom URI scheme, say) has the code but not the verifier, so the token request fails. Assumptions: authorization-code flow, a public client, TLS end to end, exact redirect-URI matching.

Mechanism. For S256, code_challenge = BASE64URL(SHA256(ASCII(code_verifier))), no padding. For plain, the challenge is the verifier itself, which only helps against an attacker who sees the code but not the authorization request. RFC 7636 makes S256 mandatory to implement on the server; if code_challenge_method is omitted the server must assume plain, which is the downgrade you don't want. RFC 9700 (OAuth 2.0 Security BCP) says use S256 only, and use PKCE for confidential clients too.

Trace (values from RFC 7636 Appendix B):

  • verifier: dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
  • challenge (S256): E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  • GET /authorize?response_type=code&client_id=...&redirect_uri=...&state=xyz&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256
  • AS redirects: 302 ...?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz
  • POST /token grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=...&client_id=...&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
  • AS recomputes S256(verifier), matches the stored challenge, issues tokens.

Generating the pair:

Python
import hashlib, base64, secrets
verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()

32 random bytes → 43 base64url characters, inside the 43–128 range.

plainS256
challenge sentverifier itselfSHA-256 of verifier, base64url
stopsattacker who sees only the codeattacker who sees the authorization request and the code
usenever in new codedefault

Failure modes.

  • Downgrade to plain. An attacker who can read the authorization request learns the verifier. Detect: reject plain at the AS and alert on any code_challenge_method=plain in logs.
  • Code replay. Codes are single-use; RFC 6749 §4.1.2 says a second redemption MUST be denied and SHOULD revoke all tokens from that code. Detect: token-endpoint logs keyed by code hash. A second hit is the signal.
  • Verifier leakage. PKCE assumes the verifier stays on the client. Written to logs, crash reports, or a shared keychain, the binding is gone. Detect: grep logs and crash dumps for code_verifier; any hit is an incident.
  • Missing state. PKCE doesn't stop CSRF on the redirect: an attacker can inject their own code into the victim's client. Detect: compare state on callback, reject mismatches.
  • Mix-up. Client sends the code to the wrong AS. Detect: OIDC discovery issuer plus exact redirect matching; AS logs show codes redeemed at an issuer that didn't issue them.

Trade-off. PKCE for confidential clients costs one hash and one parameter and defends against code injection if the redirect ever leaks; RFC 9700 recommends it. Skip it only with a measured reason and a compensating control. Authorization codes themselves should live at most 10 minutes (RFC 6749 recommendation); 30–60 seconds is common.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Compare access tokens and ID tokens.

Answer

The answer, 90 seconds in

"Start with the assumptions that matter: authorization code flow with PKCE, one issuer signing both tokens with the same RS256 key, a JWT access token per RFC 9068 rather than an opaque one, and a resource server that is not the client.

An access token is the credential a resource server accepts. It answers: may this call proceed, on whose behalf, and for what scope? An ID token is the issuer's message to the client that began the login: who authenticated, when, and by what method. It authorizes nothing at a resource server, and the client is its only intended consumer.

Two checks separate them, and neither costs a network hop. First aud: an ID token's aud is the client_id of the app that started the login; a JWT access token's aud is the resource server's identifier. Second typ: RFC 9068 section 2.1 requires a JWT access token to carry "typ": "at+jwt" in the JOSE header, while an ID token is a plain JWT or has no typ. Make the resource server require typ=at+jwt and aud=its own identifier and every ID token is rejected by construction -- that is RFC 8725 putting explicit typing (3.11) and mutually exclusive validation rules for different kinds of JWTs (3.12) to work."

Where they differ

Access tokenID token
Consumerresource serverthe client that started the login
Defined inOAuth 2.0 (RFC 6749); JWT form RFC 9068OIDC Core 1.0, validation in 3.1.3.7
Typical audhttps://api.example.comthe client_id, e.g. web-spa
typ headerat+jwtJWT or absent
Required claimsiss, exp, aud, sub, client_id, iat, jti (RFC 9068 section 2.2), plus scopeiss, sub, aud, exp, iat
Client-only claimsnonenonce, auth_time, acr, amr, at_hash/c_hash in implicit and hybrid flows
Travels asAuthorization: Bearer <token> on API callsnever as a bearer credential

The ID-token checklist is OIDC Core 3.1.3.7: iss exact match, aud contains the client_id, azp matches the client_id when aud is multi-valued, then signature and alg, then exp, iat skew and the nonce the client sent. Google's ID tokens, for instance, expire one hour after issuance -- a login event, not a grant.

Sending one where the other belongs, traced

1. Attacker registers their own public client, client_id = "evil-app",
   with the same issuer that signs the API's access tokens.
2. Login completes. Issuer returns id_token with payload
   {"iss":"https://idp.example.com","aud":"evil-app","sub":"attacker-1",
    "email":"a@evil.test","exp":...} signed RS256 with the same key.
3. Attacker calls:  GET /v1/orders
                   Authorization: Bearer <id_token>
4. Resource server that validates signature + iss + exp only: 200 OK, and
   the middleware hands `email` to the authorization layer as identity.
5. Same request against a resource server that checks aud == its own
   identifier: 401, WWW-Authenticate: Bearer error="invalid_token" (RFC 6750).

The sub is still the attacker's own user, so this is not account takeover -- it is audience collapse. The API now trusts every client of that issuer, and login-event claims the resource never asked for become authorization input. The reverse mistake costs less but bites the same way: OIDC Core 5.3.1 takes an access token at the UserInfo endpoint, so an ID token there is a 401, and an access token held on as a user profile has no nonce, auth_time or azp to check.

What it costs, and how you see it

Step 4 produces no error, so it hides quietly. Instrument both sides: log the rejected reason ("aud mismatch", "typ not at+jwt") on every 401 from the token middleware, and alert on any 2xx whose validated aud is not in the resource server's allow-list -- that single alert is the difference between a config bug and an open API. The fix itself is one line of middleware config and adds no latency, since the claim is already decoded.

JWT or opaque access token

Concrete sizes make the trade legible. A token with those eight claims: a 33-byte header and a 200-byte payload encode to 44 and 267 base64url characters, and an RS256 signature is 256 bytes, so 342 characters -- about 650 bytes on the wire, re-sent in the header of every request. Signed HS256 the signature is 32 bytes, 43 characters, and the same token is 356 bytes. An opaque reference token is 32 random bytes, 43 base64url characters, and carries no claims: 200 group memberships cannot bloat it, and it will not walk a request past Node's 16384-byte default header limit.

That is the choice. Opaque plus RFC 7662 introspection means a call to the authorization server per request unless you cache, and the cache TTL is exactly the revocation window you just gave up; in exchange, RFC 7009 revocation is immediate and the token means nothing to anyone who reads it. A JWT validates locally with no round trip, but a revoked token stays valid until exp, so keep exp in minutes. Need logout-everywhere or lockout to bite instantly and you need a denylist keyed on jti -- the claim RFC 9068 requires to be unique -- which is the call you were avoiding.

How I'd choose

Read aud first: an ID token is the only right answer when the consumer is the client asking "who just logged in?", never when the consumer is a resource server asking "may this call proceed?". Then, for access tokens, pick a JWT when validation fan-out is high and a bounded revocation window is acceptable, and an opaque token when third parties can reach the resource server, when claim payloads grow, or when revocation has to be immediate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How would you validate a bearer access token at a resource server?

Answer

First I clarify whether the token is a JWT or an opaque handle, because that decides the validation path. I assume TLS is terminated in front of the resource server, the token arrives in the Authorization header as Bearer <token>, and the resource server knows its own issuer and audience. I never accept a token from a query parameter or a cookie unless the API is explicitly designed for that.

For a JWT, I do cryptographic validation first. I parse the compact serialization, read the header, and check alg against an allowlist: RS256 or ES256, never none, and never HS256 unless the issuer and resource server share a symmetric secret. I look up the kid in the issuer's JWKS, which I fetch from the jwks_uri in the OIDC discovery document and cache. I verify the signature over the exact header.payload bytes. Then I validate claims: iss must equal the expected issuer exactly; aud must contain this resource server's identifier; exp must be in the future and nbf in the past, with a small leeway, 60 seconds is common, for clock skew; typ should be at+jwt per RFC 9068 if the issuer sets it. I check scope as a space-delimited string and then apply object-level policy: the sub must be allowed to touch the specific order or tenant in the request.

For an opaque token, I call the introspection endpoint per RFC 7662 with client authentication, and require active: true. I cache the result keyed by a hash of the token. The cache TTL is bounded by the token's exp and by a revocation window, say 30 seconds, so a revoked token stops working within that window. Negative results get a shorter TTL to avoid hammering the introspection endpoint.

The trade-off is latency versus revocation. In a typical deployment, local JWT verification is tens to hundreds of microseconds; introspection is a network hop, often 5–20 ms intra-AZ. A JWT cannot be revoked before exp unless you keep a denylist, while introspection gives you central revocation within the cache TTL. I use JWTs for short-lived, high-throughput APIs and introspection for long-lived tokens or when the authorization server must be the source of truth on every request.

Failure modes I watch for: alg=none or algorithm confusion, where an attacker strips the signature or forces HS256 with the public key as the secret. Detection is rejecting any alg not in the allowlist and logging invalid_alg. kid confusion, where the token points at a key from another issuer; I bind the issuer to the key set and never fetch JWKS from an unvalidated iss. Audience confusion, where a token for another API is accepted; I check aud exactly and log invalid_audience. Replay of a stolen bearer token; short exp, TLS, and sender-constrained tokens like DPoP or mTLS where the threat model demands it. Clock skew; the 60-second leeway plus a metric on how often it fires. Key rotation race; on an unknown kid, refresh JWKS once, then fail, and alert if refresh rate spikes.

Worked trace: token header {"alg":"RS256","kid":"2024-06","typ":"at+jwt"}, payload {"iss":"https://auth.example.com","aud":"https://api.example.com","sub":"user-123","scope":"orders:read","exp":1710000000,"nbf":1709999700}. At now=1709999800 on api.example.com: alg allowed, kid found, signature verifies, iss matches, aud contains api.example.com, exp > now, nbf <= now+60, typ is at+jwt, scope contains orders:read. Then object policy: user-123 can read order 456. If any check fails, return 401 with WWW-Authenticate: Bearer error="invalid_token". I log the failure reason and a token hash, never the token itself.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Design refresh-token handling for a first-party web and mobile client: lifetimes, rotation on every use, replay detection, concurrent devices, and where each client stores the token.

Answer

Assume OAuth 2.0 authorization code with PKCE, a first-party SPA and native app, and a server-side token endpoint that can store state. Access tokens are short-lived bearer tokens, 5 to 15 minutes, so a leaked one expires before it is useful. Refresh tokens are long-lived credentials that mint new access tokens; they live days to months but are rotated on every use.

Rotation means each refresh call returns a new refresh token and invalidates the one just used. The server stores only a hash of the refresh token, plus a family ID and the token's position in the chain. When a refresh token is presented, the server looks up its hash. If it is the current token, it issues a new access token and a new refresh token, marks the old one used, and records the new one as the child. If the presented token is already marked used, that is reuse: either an attacker replaying a stolen token or a client retrying after a dropped response. The server cannot tell which, so it invalidates the entire family: every token descended from the original grant, on that device, is revoked and the user must re-authenticate. That bounds the damage: a stolen refresh token is useful only until the legitimate client next refreshes, which triggers detection.

Concurrent devices each get their own family. A phone and a laptop have separate refresh tokens and separate chains, so rotating one never invalidates the other. The family is per-device, not per-user.

The dropped-response case is the tricky one. The client sends a refresh, the server rotates and responds, but the response is lost. The client retries with the old token. If the server treats that as reuse, it kills the family and logs the user out: a false positive. Two workable fixes: (1) a short grace window. The server keeps the immediate predecessor valid for, say, 30 seconds, and if it is presented again before the new token has been used, it returns the same new token (idempotent replay). This requires storing the new token or a deterministic derivation. (2) The client uses an idempotency key on the refresh request; the server returns the cached response for a repeated key. Either way, a second use after the new token has been used is still treated as compromise.

Storage: on web, the refresh token goes in an HttpOnly, Secure, SameSite=Lax or Strict cookie, never localStorage or sessionStorage. Those are readable by any XSS. The access token can live in memory. On mobile, use the platform secure store: iOS Keychain with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, Android Keystore-backed EncryptedSharedPreferences. Never plain SharedPreferences or a file. If the device is compromised, the attacker can read the refresh token; rotation with replay detection limits the window, and sender-constrained tokens (DPoP) or device binding raise the bar further.

propertyaccess tokenrefresh token
lifetime5–15 min7–90 days, rotated each use
storage (web)memoryHttpOnly Secure cookie
storage (mobile)memoryKeychain / Keystore
on leakexpires quicklydetected on next rotation, family revoked

Trace: user logs in → family F, token R0. Refresh → R1 issued, R0 used. Attacker steals R0, uses it → server sees R0 used, revokes F (R1 too). Legitimate client's next refresh with R1 fails → re-auth. Detection window is one refresh interval.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How do you secure browser session management?

Answer

Assumptions to state before answering. One browser app on one origin; the credential is a session ID the browser replays on every request; TLS is intact, so the attacker worth designing against can plant a cookie from a sibling subdomain, read anything you leak into a URL or log, or run XSS on your own origin. Third-party iframe embedding or a native client changes the cookie half of this answer.

Core, first 90 seconds. The ID is 128 bits from a CSPRNG (OWASP's floor is 64 bits), opaque, and the authoritative state is a server-side record: user, issued_at, auth_time, AAL, last_seen. Opacity is chosen for one reason: revocation is a single key delete, effective on the next request. A signed token stays valid to its exp whatever you later learn, so revocation ends up needing the store you were trying to avoid. Set every cookie attribute explicitly:

Set-Cookie: __Host-sid=<32 hex chars>; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800

Secure stops plaintext replay, so a network attacker is out of scope. HttpOnly keeps document.cookie blind to it, so a reflected-XSS payload cannot exfiltrate the credential; XSS can still act inside the session, so this is not CSRF or XSS insurance. __Host- makes the user agent reject any same-named cookie carrying a Domain attribute, a non-/ Path, or no Secure -- exactly the cookie-tossing vector from a compromised sibling subdomain. SameSite=Lax is not sent on cross-site POST, so evil.com's form cannot post as the user; it is still sent on top-level GET, so no GET may mutate state, and subdomain XSS counts as same-site, so keep an Origin check or a per-session synchronizer token on writes. Max-Age only limits how long a dead ID keeps being sent; the record TTL is the real expiry. Idle 30 minutes sliding, absolute 12 hours; a bank or admin console goes to 15 minutes idle and 4 hours absolute, because the record is what enforces both.

Trace: how fixation dies. Domain example.com; attacker holds XSS on old.example.com.

  1. Attacker runs document.cookie = "sid=AAA; Domain=.example.com; Path=/".
  2. Victim opens app.example.com/login. The request carries Cookie: sid=AAA.
  3. Buggy handler reuses the inbound value, so after the password check Redis holds sid:AAA -> {user:42}. The attacker replays AAA from their own browser and is the victim. That is the whole attack.
  4. Correct handler ignores client input, mints s2 from 16 CSPRNG bytes, writes sid:s2 -> {user:42, auth_time:now}, deletes the pre-auth record, and returns the header above. AAA is now a dangling value with no record, and the user agent will not even accept a Domain-carrying __Host- cookie from old.example.com.

Opaque ID vs signed token.

Opaque ID + server recordSigned token (JWT) in a cookie
Revoke on logout or password resetDELETE key, live next requestImpossible before exp without a denylist lookup
Per-request costRedis GET, ~0.5-1 ms in-VPCLocal HMAC verify, microseconds, no hop
Wire size32 hex chars300 B-1 KB, against the 4096-byte-per-cookie limit (RFC 6265 section 6.1)
Role changeRead live from the storeFrozen at issuance until refresh
Wrong whenMulti-region edge where a store hop is 30 msBanking or admin console that must kill a session instantly

Failure modes and how they show up. Redis down: logins fail and revocations silently stop working -- fail closed on privilege checks, never fall back to trusting an unverifiable cookie, and alert on GET error rate. maxmemory eviction under an allkeys-lru policy logs users out at random: run sessions on a dedicated instance with noeviction and alert on evicted_keys. Two cookies named sid in one request means cookie tossing is in progress: log and alert on it. A CI assertion that the session value in the login response differs from the one in the request catches fixation regressions.

Sizing: a 200-byte record, 5M logins/day, 30-day retention = 150M live records, roughly 30 GB before replication, plus a Redis GET on the request path. Shorten absolute TTL rather than adding a cache layer that delays revocation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you defend cookie-authenticated APIs against CSRF?

Answer

Assumptions I'd state first. The API is called from a browser, the credential is a cookie the browser attaches automatically, and at least one endpoint changes state. If any of those is false (mobile client, server-to-server, or Authorization: Bearer held in memory) CSRF does not apply, because nothing auto-attaches the credential. That is the first thing I'd confirm before adding machinery.

Core answer. Three layers, cheapest first. (1) SameSite=Lax on the session cookie, Chrome's default since Chrome 80 (Feb 2020), which stops the browser sending cookies on cross-site POST/PUT/DELETE. (2) A token the attacker cannot read: a synchronizer token bound to the session, or a signed double-submit token. (3) An Origin allowlist check on every state-changing request. Then forbid state-changing GET, because Lax still sends cookies on top-level GET navigation.

HTTP
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Lax; Path=/
Set-Cookie: csrf=8f3a...; Secure; SameSite=Lax; Path=/   # JS-readable on purpose
JavaScript
// Express 4.x + cookie-parser
app.use((req, res, next) => {
  if (['GET','HEAD','OPTIONS'].includes(req.method)) return next();
  const cookie = req.cookies.csrf;          // set by the app, readable by JS
  const header = req.get('X-CSRF-Token');   // set by the app's fetch wrapper
  if (!cookie || !header || cookie.length !== header.length ||
      !crypto.timingSafeEqual(Buffer.from(cookie), Buffer.from(header))) {
    return res.status(403).end();
  }
  next();
});

Trace. An attacker page on evil.com auto-submits <form method="POST" action="https://api.example.com/transfer">. The browser evaluates SameSite=Lax and does not attach the session cookie on a cross-site POST, so the request arrives unauthenticated and the API returns 401. If the cookie were SameSite=None, the session cookie is attached, but evil.com cannot read the csrf cookie (same-origin policy blocks it) and therefore cannot set X-CSRF-Token, so the middleware returns 403. Either way the transfer does not happen.

ControlStopsCost / caveat
SameSite=LaxCross-site POST/PUT/DELETEStill sent on top-level GET
Synchronizer tokenForged state-changing requestsServer-side session store lookup per request
Signed double-submitSame, statelessMust HMAC-sign; raw double-submit is broken by subdomain cookie injection
Origin allowlistMost cross-site requestsAbsent on some legacy clients; treat missing as reject
Custom header (X-CSRF-Token)Simple form postsForces a CORS preflight cross-origin

Trade-offs. A session-lifetime token is one lookup and one comparison; a per-request token rotated on every response kills replay of a leaked token but breaks parallel tabs unless you keep a small window of valid tokens. Raw double-submit is stateless and cheap, but an attacker who controls evil.example.com can set a csrf cookie scoped to .example.com; signing the token with a server secret, or binding it to the session ID, closes that.

Failure modes and detection. XSS in origin defeats all of this: the script reads the token and calls the API as the user. Detect via CSP report-to violations and DOM-XSS scanning; the fix is output encoding and CSP, not more CSRF tokens. Logout CSRF: GET /logout is state-changing, so require POST plus token; detect by alerting on 200s to GET /logout. CORS misconfiguration, Access-Control-Allow-Origin reflecting the request Origin with Access-Control-Allow-Credentials: true, lets any site read responses; test with a foreign Origin in CI. Token leakage via URL: keep tokens in headers, never query strings, since they land in Referer and access logs. Operationally, alert on the 403 rate from the CSRF middleware; a spike means either a broken client deploy or an active probe.

What would change the decision. If the SPA is same-site only, SameSite=Strict plus a required custom header is sufficient and the token store goes away. If you can move the credential to a Bearer token in memory, CSRF disappears entirely: you trade it for XSS token theft, which is a different problem with a different fix.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you handle logout and token revocation?

Answer

The 90-second answer

First I'd pin down what "logout" means here, because it decides the design: one device or all devices, and does the access token have to die immediately or is a short window acceptable? My default assumption is a browser app with a session cookie, short-lived JWT access tokens, and a server-side refresh token.

Logout has to do three things, and only the first is free.

  1. Clear client state: the session cookie (Set-Cookie: sid=; Max-Age=0; HttpOnly; Secure; SameSite=Lax) and any tokens held in memory. Necessary, not sufficient.
  2. Kill the server-side artifact: delete the session record, or revoke the refresh-token family. This is the step that actually ends the session, because the refresh token is what mints new access tokens. Clear only the cookie and anyone holding a copy of the refresh token keeps minting.
  3. Decide what to do about the access token already in flight. A JWT is self-contained: the resource server checks the signature and exp and never calls back. It stays valid until it expires. Typical access-token TTLs are 5–15 minutes (Keycloak's default is 5 minutes, Okta's is 1 hour), and that is the revocation window you are accepting.

If that window is unacceptable (banking, admin consoles, anything where "account disabled" must mean "now") you need a check on every request. Three options, in increasing cost:

approachhow it workscost per requestpropagation
denylist by jtiRedis key revoked:{jti}, TTL = remaining token lifetimeone Redis GET, order 0.2–0.5 msimmediate
token version / iat cutoffuser record holds token_version; token carries it; bump on logout-allone cache read of the user recordimmediate, coarse
introspection (RFC 7662)resource server POSTs the token to the auth servernetwork round trip, order 5–20 ms; auth server becomes a hard dependencyimmediate

The denylist is the usual pick. The TTL is the whole trick: set it to the token's remaining lifetime, not a fixed 24 hours, or the list grows without bound and Redis starts evicting entries that are still live.

Failure modes I'd watch

  • Rotation race. With refresh-token rotation and reuse detection (the OAuth 2.0 Security BCP), two tabs refreshing at once means the second presents an already-rotated token, the server reads it as theft, and revokes the whole family. Trace: at t=0 tab A refreshes with RT1, server issues RT2 and marks RT1 used; at t=0.3 s tab B refreshes with RT1, server sees RT1 reused, revokes the family including RT2, and both tabs get 401. Detect it as a spike in invalid_grant on the token endpoint right after a rotation change; fix with a few-second grace window on the previous token, or serialize refresh in the client.
  • Clock skew. If the issuer revokes at T and a resource server's clock is 40 s behind, it still accepts. Log the distribution of exp - now at validation time; if the tail is wide, allow 30–60 s leeway and keep TTLs well above it.
  • Multi-device surprise. Logging out on the phone leaves the laptop session alive. That is correct for a per-session model and wrong for "log me out everywhere". Expose a session list plus a separate revoke-all that bumps the token version.
  • Denylist outage. If Redis is down and you fail open, revocation silently stops working. Fail closed for admin scopes, fail open for read-only, and alert on the error rate so it is not invisible.

I'd also write the window down explicitly in the security doc: "revoked sessions stop minting new tokens immediately; existing access tokens remain valid for up to N minutes." That sentence is what an auditor asks for.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do you prevent user enumeration in authentication flows?

Answer

I'd ask two things first: is the scope just the login form, or the whole lifecycle. Signup, reset, invites, SSO discovery? And how much latency noise can the attacker average away, since that sets how tight the timing has to be? Assume login, signup, reset and an email-domain SSO entry point, with an attacker who reads bodies and headers and times responses. The answer: equalise every observable (status code, body bytes, headers, and the CPU work actually performed) between accounts that exist and accounts that don't, and keep the reason in internal logs.

The leak most teams miss is work, not wording. A login handler looks the user up, then verifies the password; when the lookup finds nothing there is no hash, so it returns early. Argon2id at m=19 MiB, t=2, p=1 costs roughly 50 ms on a current server core, and the indexed lookup about 1 ms. Existing account: about 51 ms. Absent account: about 1 ms. A 50x gap survives plenty of jitter; twenty requests per address separate the two distributions.

DUMMY_HASH = argon2.hash(randomBytes(32))   // once at boot, same params as real hashes

async function login(email, password) {
  const user = await db.findUserByEmail(email);
  const stored = user ? user.passwordHash : DUMMY_HASH;
  const ok = await argon2.verify(stored, password);      // runs either way
  if (user && ok) return issueSession(user);
  log.warn({ email, reason: user ? 'bad_password' : 'no_user' });  // internal only
  return unauthorized('Invalid email or password');      // byte-identical either way
}

Trace it. Existing email, wrong password: the lookup returns a row, stored is the real hash, verify returns false, user && ok fails on ok, so we log bad_password and return the 401. Absent email: the lookup returns null, stored is DUMMY_HASH, verify still burns its roughly 50 ms and returns false, user && ok fails on user. Log no_user, same 401. One lookup and one hash on both paths. Build that 401 body as a constant at boot rather than from user fields, so Content-Length and header order match too.

Reset and signup follow the same rule. The reset request always answers 200 with 'If that address is registered, a link is on its way.' and the mail goes onto a queue: a synchronous SMTP handshake and template render adds 100-300 ms the client can see. Signup never says the address is taken: create the pending row, send to that address, and if a confirmed account exists the mail reads 'someone tried to register your address'. Same 202, same body, both times.

Rate limiting is where enumeration comes back in. A per-account counter that answers 'Too many attempts for this account' is itself a probe: hammer an address and a 429 means it exists. Key the limiter on source IP plus a device cookie, return the same generic error, and spend the bucket identically for an address that doesn't exist. NIST SP 800-63B (5.2.2) caps consecutive failed attempts on one account at 100, but per-account lockout alone is a denial of service aimed at your own user, so pair it with per-source throttling and a short increasing delay.

Three channels still get missed. Email-domain SSO discovery: 'enter your work email' that redirects known domains to Okta and errors otherwise enumerates your customer list. Send unknown domains to the same password page, and never pass an identity provider's user_not_found through to the browser. Cache headers, if the endpoint is cacheable at all: X-Cache: Hit versus Miss and the Age header differ between a warm and a cold response, so the second probe of a real account returns measurably faster. And signup availability widgets: 'is this username free' on every keystroke is an enumeration API by design. Check on submit and return the pending-account response.

Detection: run the probe in CI. Send the same request against a seeded account and a random address in staging, diff status, body hash, header set and p50/p99 latency, and fail the build on a body-hash mismatch or a latency gap over 20%. In production, alert on one source touching many distinct addresses: that is what enumeration looks like before it turns into credential stuffing.

None of this stops credential stuffing or removes the need for MFA and breached-password screening. It does cost support clarity: the reason codes stay in internal logs and must never be reachable from the response template.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do you design secure account recovery?

Answer

Assumptions: consumer SaaS, email plus optional TOTP/passkey, a support desk, no in-person verification. Recovery is authentication with a weaker proof, so it needs its own assurance level and its own controls, not a shortcut bolted onto the login endpoint.

Core answer. Rank evidence by strength and require the strongest thing the user still has: an existing authenticated session or trusted device first, then single-use recovery codes, then an email magic link, then SMS last. Never knowledge-based questions. Each recovery path is a separate endpoint with its own rate limits, its own token type, and its own notification.

Why KBA fails: the answers are commodity data. Mother's maiden name, prior addresses and SSNs are sold by data brokers, so the "secret" is public. NIST SP 800-63B prohibits knowledge-based authentication, and revision 4 removes it entirely.

Token mechanics. A reset token is 128 bits from a CSPRNG, stored only as a SHA-256 hash, TTL 15 minutes, single-use (deleted on consume), and bound to account and purpose:

token = HMAC(server_key, account_id || purpose || issued_at || nonce)

Purpose-binding matters: without it, a token minted for "verify email" replays against the "reset password" endpoint. Account-binding stops a token for A being used on B. Issuing a new token invalidates the previous one.

Rate limits and enumeration. 5 reset requests per account per hour, 20 per IP per hour, exponential backoff after. The endpoint returns the same body and comparable timing whether or not the account exists: otherwise it is an account-enumeration oracle.

Notification and delay. Every recovery event emails and pushes to all existing sessions, with a "this wasn't me" link that revokes. Email and phone changes go on a 24–72 hour hold with a cancel link to the old address; the new contact cannot be used for recovery until the hold clears.

Session handling. A password reset revokes all refresh tokens and sessions except the one performing it, and rotates the session ID.

Support override. Two-person rule, callback to the number already on file, immutable audit log, and an appeal path.

Trade-offs. Email-only recovery is cheap and self-service but email compromise becomes account takeover. Recovery codes are strong but users lose them. SMS is convenient but SIM-swappable: NIST SP 800-63B marks it RESTRICTED. Support-only recovery resists automation but invites social engineering and costs money per ticket. The deciding criteria are account value, attacker motivation and support capacity: a bank account justifies the 72-hour hold and callback; a free forum account does not.

Failure modes and detection.

  • SIM swap: carrier port-out webhook, or a phone change followed by a password reset within minutes → alert and freeze.
  • Support fraud: one agent's override rate spiking above baseline → review.
  • Token replay: a second use of a consumed token → log and revoke.
  • Enumeration: response-size or timing differences between existing and non-existing accounts → alert.
methodassurancemain failure
existing session/devicehighstolen device
recovery codeshighuser lost them
email linkmediumemail compromise
SMSlowSIM swap
support overridevariablesocial engineering

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you implement step-up authentication?

Answer

Core answer

Step-up authentication re-verifies the user at a higher assurance level at the moment they attempt a sensitive action, inside the session they already have. It is not a second login and not a role change: authorization still runs afterward. Three decisions decide the implementation: what triggers the step-up, what assurance you demand, and how long the elevation lasts.

Assume an OIDC IdP, a browser session cookie, and NIST SP 800-63B AAL levels as the vocabulary. A normal login is AAL1 or AAL2; a $50k payout or an authenticator change demands AAL3: a phishing-resistant authenticator such as a WebAuthn/passkey credential.

Trigger and policy

Map each action to a required assurance and a freshness window. Freshness is the auth_time claim in the ID token: how long ago the user actually authenticated.

ActionRequired AALMax auth_age
View balanceAAL1session lifetime
Change email/passwordAAL25 min
Payout > $10kAAL35 min
Add/rotate admin keyAAL32 min

If the session's acr/amr and auth_time already satisfy the row, proceed. Otherwise step up.

Mechanism

  1. Persist intent server-side. Write the pending action to a row keyed by a transaction ID (amount, payee, form fields) before redirecting. This is why intent preservation matters: a redirect to the IdP drops the POST body, and re-asking the user to re-enter a wire transfer is how you get them to abandon it or to approve a re-rendered form that differs from what they submitted.
  2. Redirect to the IdP with acr_values set to the required level, max_age set to the freshness window, and prompt=login. acr_values asks for the level; max_age forces reauthentication if the last one is too old.
  3. On return, verify the ID token: signature, acr meets the requirement, auth_time within the window, and the transaction ID matches the one you stored. Binding success to the transaction is what stops a replay: an elevated token minted for payout A must not authorize payout B.
  4. Rotate the session ID on elevation. Otherwise a session-fixation attacker who planted a cookie before login inherits the elevated state.
  5. Set elevated_until on the session (5 minutes for the payout, 2 for key rotation) and re-check it on every sensitive action, not just the first.

Trade-offs

Phishing-resistant (WebAuthn) beats phishable (TOTP, SMS, push). SMS is SIM-swappable; push is subject to MFA fatigue. Use WebAuthn for AAL3 actions; accept TOTP only where the action is reversible. Short windows are safer but annoying: 5 minutes covers a single transaction, while a 30-minute window means a stolen cookie keeps elevated rights for 30 minutes.

Failure modes

  • MFA fatigue: an attacker spams pushes. Detect via push rate and number matching; cap at roughly 5 pushes.
  • Elevated state too long: a stolen session cookie retains AAL3. Keep windows short and re-check per action.
  • Failed or cancelled step-up: rate-limit (e.g., 5 attempts, then backoff) and audit, returning the same error whether the account exists or not.
  • Recovery bypass: account recovery must not silently grant the assurance the step-up demanded.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How would you authorize service-to-service calls?

Answer

Assumptions: east-west traffic inside one trust domain, a Kubernetes cluster or a mesh, with no end user in the path. If a user's request is being delegated, that's a second identity layered on top; I'll come back to it.

Split the problem in two. Identity answers which workload is on the other end of this socket. Policy answers may that workload do this. A valid identity is not an authorization, and conflating them is how you end up with a service that can call anything because it authenticated.

For identity, the strongest option is mTLS with SPIFFE IDs issued by SPIRE. Each workload gets an X.509 SVID whose URI SAN is spiffe://<trust-domain>/ns/<ns>/sa/<serviceaccount>. The SPIRE agent on each node attests the workload (via the kubelet's projected service account token, or a unix socket path) before handing it a cert, so the identity is bound to the process, not to a secret someone copied. The SVID is short-lived: SPIRE's default default_svid_ttl is 3600s and the agent rotates at half that, so a leaked key is useful for at most 30 minutes.

The receiving side terminates TLS, validates the chain against the SPIRE trust bundle, and reads the SPIFFE ID out of the URI SAN. No bearer token exists to steal, because the identity is the key that completed the handshake.

For policy, evaluate the peer SPIFFE ID plus the request. In Istio that's an AuthorizationPolicy:

YAML
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata: {name: payments-from-checkout, namespace: prod}
spec:
  selector: {matchLabels: {app: payments}}
  action: ALLOW
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/prod/sa/checkout"]
    to:
    - operation: {methods: ["POST"], paths: ["/v1/charge"]}

Trace a call: checkout's sidecar opens TLS to payments and presents its SVID. Payments' sidecar verifies the chain, extracts .../sa/checkout, and Envoy matches the rule: POST /v1/charge, allow. If checkout instead sends GET /v1/refunds, no rule matches, Envoy returns 403 with RBAC: access denied, and the decision lands in the access log. That log line is the audit trail: caller SPIFFE ID, method, path, verdict.

Crossing a trust domain (a partner, or a service outside the mesh) you can't share a CA, so use OAuth2 client credentials: the caller authenticates at the AS and gets a JWT access token with aud set to the callee. The callee validates signature, exp, iss, and aud. Audience binding is the whole point: a token minted for payments is rejected by inventory even if it leaks, which kills the confused-deputy replay where a low-value service's token gets replayed against a high-value one. Keep the TTL to 5–15 minutes and rotate the client secret from a secret manager.

OptionGives youCostsUse when
mTLS + SPIFFE (SPIRE)Per-connection cryptographic identity, no bearer token, automatic rotationControl plane (SPIRE server + per-node agent), attestation to configure, no user contextBoth ends are in your trust domain and can run an agent or sidecar
OAuth2 client credentials (JWT)Works across trust domains and through gateways, carries claimsBearer token: replayable until exp; needs audience checks and short TTLCross-org, or a caller that can't do mTLS
Static API keyTrivial to implementNo expiry, no rotation, leaks in logs and configsLast resort; scope it, store it in a secret manager, rotate on a schedule

Failure modes worth naming:

  • Over-broad registration entry. A SPIRE entry with a selector like unix:uid:0 hands an SVID to anything running as root on the node. Detect by diffing registration entries in CI and alerting on any entry whose selectors aren't a specific service account.
  • Stolen JWT replayed. Same jti seen from two source ASNs. Detect at the gateway by counting distinct source IPs per jti; the short TTL bounds the window.
  • Clock skew. SVID validation fails with certificate has expired or is not yet valid at one or two minutes of skew. Detect as a cluster-wide spike in TLS handshake failures on a single node.
  • SPIRE agent down. SVIDs stop rotating and every workload on that node fails at TTL expiry. Alert on agent health and on SVID age approaching TTL.
  • Policy drift. Allowed callers grow quietly. Count distinct caller SPIFFE IDs per callee per day from the access log and alert on new pairs.

Delegation: when a user's request rides along, carry two identities, the service actor and the end user, in a token the callee can verify, and authorize on both. The service's own identity must not stand in for the user's.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design authorization for a multi-tenant invoice API.

Answer

Assumptions: Postgres 16, JWT access tokens from an OIDC IdP, services in Go, policy in OPA (Rego v1). Tenant id is a UUID; invoices has tenant_id uuid not null.

First 90 seconds. Never take tenant or user from the request body or query string. Derive the subject from the verified token's sub claim, and the active tenant from a server-side membership lookup keyed by sub plus the token's tid claim. If tid isn't in the membership set, reject with 403 before any data access. Then every repository method takes (tenant_id, subject) and applies two independent gates: a query predicate and a policy decision. Deny is the default: the policy engine returns deny unless an explicit rule allows, so a new action or a new resource type fails closed.

Mechanism. Three layers, each catching what the one above misses.

  1. Query scoping. Every statement carries WHERE tenant_id = $1. Cheapest gate, and the one that survives a policy bug.
  2. Policy decision. OPA evaluates (principal, action, resource) with the resource loaded under the tenant scope. A read rule:
REGO
allow if {
  input.action == "read"
  input.principal.tenant == input.resource.tenant
  input.principal.role == "admin"
}
allow if {
  input.action == "read"
  input.resource.owner == input.principal.user
}
  1. Database RLS as defense in depth. Postgres 16:
SQL
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id')::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

The app runs SET LOCAL app.tenant_id = $1 inside the transaction. FORCE matters: without it the table owner bypasses RLS, which is the classic way this layer silently does nothing.

Trade-offs. Centralized policy (OPA/Cedar) vs per-service checks vs RLS-only:

approachwinscostspick when
Centralized policyone place to audit, consistent across servicesin-process eval is sub-millisecond, a sidecar adds ~1–3 ms p99; policy language to learnmany services, compliance needs a single answer
Per-service checksno extra dependency, lowest latencydrift between services, easy to forget a pathone or two services, small team
RLS onlycannot be bypassed by app codehard to express ownership/state rules, per-connection SET overheaddefense in depth, not the primary gate

RLS alone can't express "owner or admin, and only when invoice state is draft" without contorting SQL. Use it as the floor, not the ceiling.

Failure modes.

  • Stale membership. A user removed from a tenant keeps a valid token for its remaining TTL. Check membership server-side per request, or keep TTL ≤ 5 min and maintain a revocation set. Detect: audit rows where sub acts on tid with no membership row.
  • Ownership transfer race. Two requests read owner = A, both write. Use optimistic concurrency: UPDATE invoices SET owner = $1, version = version + 1 WHERE id = $2 AND version = $3; zero rows affected means retry.
  • Bulk and background paths. A 10k-row export that checks only the list scope leaks rows if any row's tenant differs. Check per object, or batch by tenant. Background jobs have no user token: give them a service principal with an explicit tenant scope, never a wildcard.
  • Cache invalidation. Cached decisions keyed by (sub, tid, action, resource_id) go stale on role change. Include a policy_version in the token or cap TTL at 30 s.

Hypothetical arithmetic. 10k invoices, in-process OPA check at ~50 µs each = 500 ms; batching 500 rows per check = 10 checks, ~0.5 ms. That's the difference between a p99 you can ship and one you can't.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Where must authorization run in GraphQL, WebSockets, and background jobs?

Answer

Assumptions: enforcement is server-side only. Client checks are UX. The callers are already authenticated at the edge with a signed identity, the system is multi-tenant, and policy is deny-by-default.

What a strong candidate says first

Put the check where the data is selected, not where the request enters.

GraphQL: authorize every field and nested edge at the resolver or the data layer. { me { org { members { email } } } } is four decisions, and a permitted parent says nothing about the child. WebSockets: authorize the handshake once, then every operation and every event that changes what that socket sees. A connection outlives the token that opened it. Background jobs: authorize twice. Once at enqueue to capture who asked, once at execution to re-decide against current policy, because the gap between those points is the entire risk. Anything that fans out over rows needs a per-item decision, and no path may fall back to the scheduler's own service credentials when a check fails.

Picking a placement

placementcatches a new field by defaultcan express row/tenant scopecosthow it fails
schema directive (@requiresScopes, Federation 2.5+)nono: scopes only~0, evaluated before the resolvera new field ships with no directive and is public
middleware (graphql-shield)only inside the wrapped resolver mapnoone rule evaluation per fielda resolver added outside the map is unprotected
data layer (Postgres RLS with SET LOCAL app.current_tenant, scoped repositories)yesyesone policy evaluation per row, one extra statement per transaction"not found" and "not allowed" collapse into the same null

Use the directive as a cheap coarse gate and the data layer as the backstop. Note the directive is a filter, not a grant: with @requiresScopes(scopes: [["read:products"]]) the inner array is AND and the outer array is OR, and the caller still needs the row check.

WebSockets (graphql-ws v5, graphql-transport-ws)

JavaScript
useServer({
  onConnect: async (ctx) => {
    const claims = await verifyAccessToken(ctx.connectionParams?.Authorization?.slice(7));
    if (!claims) return false;                       // close 4403 Forbidden
    return { userId: claims.sub, scopes: claims.scope.split(' ') };  // lands in ctx.extra
  },
  context: (ctx) => ({ userId: ctx.extra.userId, scopes: ctx.extra.scopes }),
  onSubscribe: async (ctx, msg) => {
    // walk msg.payload.query's selection set (helper omitted); map field -> required scope
    for (const f of fieldsOf(msg.payload.query))
      if (!ctx.scopes.includes(f.requiredScope)) return new Error('forbidden: ' + f.name);
  },
}, ws);

Trace: the client sends connection_init with { Authorization: "Bearer <expired>" }. onConnect verifies, gets nothing, returns false, and the server closes with 4403 without ever sending connection_ack: no subscription can be established. A valid token gets connection_ack, and each subscribe frame re-enters onSubscribe, so a subscribe to org(1).members.email is rejected even though the connection is authenticated. Browsers cannot set an Authorization header on new WebSocket(), which is why the token rides in the connection_init payload or a cookie rather than a header.

Failure mode: authorizing once at handshake. A member is removed at T; the socket keeps receiving memberAdded because the shared Redis channel is authorized at publish time, not per subscriber. Re-check on each subscribe and on a heartbeat or policy-change event, then close with 4401.

Background jobs

Enqueue at 09:00 for actor U (editor at tenant T), action export:reports. Executes at 15:00.

  • Token minted 08:45, expires 09:15. An expired token in the payload is evidence of nothing; do not store it as a grant.
  • U's editor role is revoked at 10:30.
  • At 15:00 the worker reloads U's current grants, finds no editor, and fails closed with denied: role_revoked on the audit record.

So the payload carries subject id, tenant, action, policy version and an idempotency key, not a token, not a role snapshot, not the worker's ambient service account. Where the worker does need cloud calls, the confused-deputy fix is sts:AssumeRole with Tags: [{ Key: "subject", Value: U }] plus an IAM condition on aws:PrincipalTag/subject. Two boundaries: a machine-owned job with no human actor (nightly reindex) should not be reauthorized against a user at all. Give it a dedicated least-privilege identity, e.g. a Kubernetes serviceAccountName per CronJob with automountServiceAccountToken: false when it needs no API access; and a fan-out job iterating records must filter per record, because the enqueue-time grant covered the request, not every row it later touches.

Detect all of this the same way: an audit line per decision containing subject, action, resource, policy version and allow/deny, so a denied-at-execution job is visible rather than silently skipped. If policy is unreachable, the job retries; it does not proceed on the worker's default privileges.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How should authorization decisions be cached?

Answer

Assumptions first: I'm caching the result of a single check ((subject, action, resource) → allow/deny) and the thing I'm actually afraid of is a stale allow after a revocation. So the first question isn't "what TTL", it's "what's the revocation SLA?" If it's "immediate" (offboarding, break-glass, a payment above a threshold) that path doesn't get cached at all. Everything else does.

The key has to contain every input the policy reads, not just the obvious three. Subject id plus tenant plus session/MFA level, action, resource id, and any context the policy branches on: source IP range, time window, resource owner, resource attributes. If the policy reads it and it isn't in the key, you serve a decision computed under different inputs. Tenant belongs in the key even when subject ids are globally unique: one missing tenant prefix is a cross-tenant leak.

Then the invalidation strategy, which is the real decision. Three options:

  • No cache. Correct by construction, and fine if the policy store can take the load.
  • Short TTL. Simple, no invalidation plumbing, but worst-case staleness equals the TTL, and entries expire independently so you can't revoke faster than that.
  • Versioned invalidation. What Zanzibar-style systems do. A write returns a consistency token: a zookie in the Zanzibar paper, a ZedToken in SpiceDB, the consistency preference on OpenFGA's Check API. A read carrying that token is guaranteed to reflect at least that write. So the cache entry stores the token it was computed at; on lookup you compare it to the current token and recompute if it's behind. Revocation becomes "bump one counter" instead of "find and delete N keys."

Where the cache lives matters too: a sidecar cache in the enforcement path saves the network hop but invalidation has to fan out to every pod; a centralized Redis is one invalidation but adds a hop and a new dependency on the hot path.

Versioned invalidation gives fast revocation but invalidates a whole scope at once, so a policy write for a big tenant can stampede the store. The usual fix is a hybrid: version token for correctness, plus a short TTL with jitter so entries don't all expire together, plus single-flight so concurrent misses on the same key collapse into one store call.

Worked example, hypothetical numbers. Check endpoint: 40k checks/s, policy store good for 3k QPS. Uncached, the store saturates and p99 goes from 8 ms to seconds. With a 30s TTL and a measured 99.5% hit rate, 200 checks/s reach the store: comfortable. But worst-case revocation is now 30s. If the SLA is 5s, TTL alone fails and you need the version token. Note the cost of the token: every policy write invalidates that tenant's entries, so a tenant doing 50 writes/s against a 1M-entry working set is effectively running uncached.

Failure modes and how I'd catch them:

  • Stale allow after revocation. Measure it: grant, revoke, poll the check endpoint, record the delta. Alert when p99 propagation exceeds the SLA. This is the metric that tells you the cache is wrong, and it's the one people forget to instrument.
  • Deny-cache poisoning. If the policy store times out and you cache the resulting deny, a 2-second blip becomes a 30-second outage for those users. Never cache a decision that came from an error: only from a completed evaluation.
  • Stampede on version bump. Detect via store QPS spikes correlated with policy writes; mitigate with jitter and single-flight.
  • Clock skew across regions. TTLs computed from local clocks expire at different times; prefer the version token, or monotonic clocks.

Fallback: fail closed for writes and anything sensitive; fail open only for low-risk reads, and then only to a last-known-good entry inside a short grace window. Be explicit that fail-closed means an authz outage is a full outage: that's a business decision, not a caching one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you enforce field-level authorization and safe data exports?

Answer

The 90-second answer. Object-level checks answer "may this subject touch this row?" Field-level authorization answers a different question: "given why they are asking, which columns may leave the database?" Keep them as separate gates, and make the second one server-owned. The client names a purpose, never a field list, and the server maps purpose → allowlist. Exports are not a bigger read; they are a separate path with their own permission, row cap, and delivery channel.

Concretely, a projection function that intersects a purpose allowlist with the subject's grants, applied as the last step before serialization:

Python
# Python 3.12
READABLE = {
    "support": {"id", "email", "plan", "created_at"},
    "billing": {"id", "plan", "mrr_cents", "vat_id"},
}

def project(row, grants, purpose):
    allowed = READABLE[purpose] & grants
    return {k: v for k, v in row.items() if k in allowed}

Trace it. Row from users:

{"id": 7, "email": "a@b.c", "plan": "pro",
 "mrr_cents": 4900, "vat_id": "DE123", "ssn": "078-05-1120"}

Support agent, grants = {"id","email","plan","created_at"}, purpose="support": allowed = {"id","email","plan","created_at"}, output {"id": 7, "email": "a@b.c", "plan": "pro"}. mrr_cents, vat_id and ssn never reach the serializer. Same row, purpose="billing", grants {"id","plan","mrr_cents"} → {"id": 7, "plan": "pro", "mrr_cents": 4900}. vat_id stays behind even though billing normally sees it, because this subject's grant set is narrower than the purpose.

LayerEnforcesCostWhere it leaks
PostgreSQL column GRANTcolumn read/write per rolefree, DDL onlyrole explosion; no purpose or consent dimension
RLS policyrow scope per session varone policy per tablenot column-level; views need security_barrier
Service projectionpurpose + subject grantsone function per resourceany path that skips it: raw SQL, admin shell
Field encryptionthe column itselfbreaks sort and searchkey management

Use DB grants as the floor, projection as the default-deny layer, encryption only for the two or three columns where a leak is a breach (SSN, card PAN).

Exports: separate permission, not a wider read. Cap rows (50k), rate limit (5/hour/subject), and re-check policy when the async job writes, not when it was queued: a job queued at 09:00 and written at 09:40 must not run on 09:00 grants. Deliver through a 15-minute presigned URL with a one-time token, expiry, and an audit row carrying subject, purpose, row count and a hash of the field list. Escape CSV cells starting with =, +, - or @ (prefix '), or Excel executes them.

Aggregation is the leak people miss: a sum over a filtered set containing one row reveals that row. Suppress groups under 5 rows.

When this is too heavy: a single-tenant internal admin with three operators needs a column GRANT and an audit log, nothing more. A policy engine there is maintenance with no threat model behind it.

Failure modes and how to catch them:

  • Serializer drift. Someone adds ssn to the model and DRF exposes it. Detect with a CI test that diffs serializer fields against the allowlist and fails on any new name.
  • Cache keyed by object id only. Revoking a grant does not invalidate the entry. Key on (object_id, policy_version) and bump the version on every grant change.
  • 403 vs 404. Returning 403 for a row you cannot see confirms it exists. Return 404 for both.
  • Search index built from the base table. Index the projection instead, and test the mapping in CI.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you authorize tenant migration or resource ownership transfer without race-condition leaks?

Answer

Clarify and assumptions

Assume a multi-tenant SaaS on PostgreSQL 16, default READ COMMITTED, with a resources table carrying tenant_id and owner_version. Authz reads the canonical row, never a client-supplied tenant field. Transfer is rare; writes per resource are moderate. The goal is that at no instant can a source-tenant principal or a stale async job act on the resource after the commit point.

Core answer

Make transfer a single-row compare-and-swap. The write that changes ownership also enforces the old owner and version, so a concurrent authz check cannot leak.

SQL
BEGIN;
UPDATE resources
SET tenant_id = 'dest', owner_version = owner_version + 1
WHERE id = 'r1' AND tenant_id = 'src' AND owner_version = 7
RETURNING owner_version;
-- if no row returned: ROLLBACK
-- else: INSERT INTO outbox(event_type, resource_id, owner_version) VALUES (...); COMMIT;

Trace two concurrent transfers, T1 and T2, both reading version 7:

  1. T1 executes the UPDATE. The row matches tenant_id='src' and owner_version=7. PostgreSQL locks the row, sets tenant_id='dest', owner_version=8, returns 8. T1 commits.
  2. T2 executes the same UPDATE. Under READ COMMITTED, T2 blocks on T1's row lock. After T1 commits, T2 re-evaluates the WHERE on the new row: tenant_id='dest' and owner_version=8. The condition fails. T2 gets 0 rows and rolls back.
  3. If T2 had acquired the lock first, T1 would fail instead. Exactly one transfer commits.

After commit, bump the version in every cache key: authz:{tenant_id}:{resource_id}:{owner_version}. Old keys become unreachable; set a 60s TTL as a backstop. Subscriptions, share links, exports, and queued jobs carry resource_id and owner_version; each reauthorizes against the current row before acting. A job from the source tenant sees version 8 and drops or re-routes.

Freeze vs reconcile

ApproachDeciding criteriaCostWhen to use
Freeze writesWrite rate per resource < 500/s; strict consistencySource writes get 409/423 during the window; queue backlogLow write rate, simple authz, no idempotent replay
Reconcile writesWrites are idempotent; durable log exists; high write rateReplay complexity, conflict resolution, risk of missed replayHigh write rate, can tolerate eventual consistency

Hypothetical arithmetic: 10k resources, 200 writes/s, 30s freeze = 6,000 queued writes. If the queue drains at 500/s, that is 12s of backlog. Reconcile avoids the freeze but needs an idempotency key per write and a durable log; if replay misses one write, the source tenant can leak access. Do not reconcile when writes are not idempotent or the log is not durable.

Failure modes and detection

  • Lost update: two admins transfer the same resource. CAS prevents it; detect by counting owner_version jumps > 1 per resource per minute.
  • Stale authz cache: old version still served. Detect authz_version_mismatch_total; alert if > 0 for 5 minutes.
  • Queued job from source: job reauthorizes and sees new tenant. Detect job failure rate for resource_id during transfer window.
  • Share link or export: link includes old version. Old version returns 403; detect 403 spike on resource_id.
  • Audit reconciliation: run
SQL
SELECT g.resource_id
FROM grants g
JOIN resources r ON r.id = g.resource_id
WHERE g.tenant_id <> r.tenant_id;

This must return 0 rows. If it returns any, a source or unrelated tenant retained access.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you design safe administrator impersonation?

Answer

What I'd say first

Before designing anything I'd pin down what support actually needs to do. My assumption: multi-tenant SaaS, support engineers need to see and sometimes act on a customer's account, SSO with WebAuthn is already in place, and there's an audit pipeline. Under those assumptions the answer is: impersonation is a separate, short-lived, scoped token that carries two identities, the real actor and the effective subject, never a role switch on the admin's own session.

Mechanism

The grant is issued by a dedicated service, not by the admin's session. It checks four things: a WebAuthn assertion within the last 5 minutes, a ticket ID, an approval for tier-2 tenants and above, and that the target principal is not more privileged than the actor. It then performs an OAuth 2.0 token exchange (RFC 8693) and issues a token where sub is the customer user and act.sub is the support engineer. TTL 30 minutes, hard cap 60, no renewal without a fresh approval.

Every downstream service authorizes data scoping on sub and writes the audit record from act. That's the point of a separate token rather than a role switch: with a role switch the session identity is the admin, so a service that scopes by sub either shows the admin's own data or needs a side channel to learn who is being impersonated, and the audit log ends up with one identity. With the act claim both identities travel on every hop and are checkable at each one.

Python
# Python 3.12
def resolve_identity(claims: dict) -> Identity:
    impersonating = "act" in claims
    actor = claims["act"]["sub"] if impersonating else claims["sub"]
    subject = claims["sub"]
    if impersonating:
        if actor == subject:
            raise Deny("actor and subject identical")
        if not claims.get("imp_ticket"):
            raise Deny("impersonation token without ticket claim")
    return Identity(actor=actor, subject=subject, impersonating=impersonating)

Audit record: {"actor":"eng:alice","subject":"user:42","imp_ticket":"SUP-8812","scope":["orders:read"],"corr":"..."}.

Alternatives

approachattributionper-user scopingcost
shared break-glass adminnonenonezero code
role switch in admin sessionone identityneeds side channellow
impersonation token with actbothnativetoken exchange + every service reads act

Don't build it at all when the workflow is read-only: a scoped export or a customer-consented screen share removes the write path and the permanent attack surface with it.

Failure modes and how I'd detect them

  • Stale grant: ticket closed, session still alive. Alert when impersonation_session_age_seconds > grant_ttl; nightly join of open sessions against closed tickets.
  • Actor/subject collapse: a service reads only sub, so the audit line names the customer as the actor. Contract test that every audit emitter sets actor; alert on any event with impersonating=true and actor==subject.
  • Exit-path escalation: the exit endpoint re-issues a session from a refresh token that was rotated or widened during impersonation. Capture the scope set at entry, compare on exit, alert on a superset.
  • Impersonating a peer admin: support engineer targets a tenant admin and inherits admin APIs. Deny at grant time when target role rank ≥ actor role rank; alert on attempts.

What would change my answer

If tenants can consent per session, the customer clicks "allow support for 30 minutes", consent becomes the authorization and I'd drop the approval tier. If the workflow is read-only, I'd ship the export and not build impersonation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design break-glass access for an operational emergency.

Answer

Core answer (first 90 seconds)

Two things decide this design before any control list: what class of emergency it covers, and whether the identity provider is assumed to be up. If the emergency is "the IdP is down," a break-glass path that authenticates through the IdP is useless: the path must not depend on the systems it exists to rescue. So I'd assume the IdP may be unavailable, one or two named responders, and the credential is a FIDO2/WebAuthn hardware key in a physical safe, not a password in the same vault as the systems it unlocks.

The design: a dedicated role nobody holds standing access to. The responder takes the key from the safe, authenticates with it, and assumes the role for a 1-hour session, not the 12-hour maximum AWS allows. The session carries the incident ID as a session tag, so every API call is attributable to a person and a ticket. Expiry is the primary control: when the STS session ends the credential stops working, so there is nothing to revoke.

Mechanism, control by control

ControlMechanismFailure it prevents
1h session TTLsts:AssumeRole DurationSeconds=3600; the temporary credential expires on its ownA session left live for days after the incident closes
Incident ID as session tagsts:TagSession puts the ticket into userIdentity.sessionContext on every CloudTrail event"Who did this, and under what ticket?" unanswerable afterwards
Page on assumeEventBridge rule matching the role's AssumeRole → on-call pagerSilent use
Revocation by token ageIAM policy denying actions when aws:TokenIssueTime is older than the revocation timestampYou cannot revoke an STS session directly; this is how you kill one mid-flight
Dual control on destructive opsSeparate approval step (Step Functions, Azure PIM approval, GCP Access Approval) gating delete/terminateOne responder fat-fingering a teardown at 3am

Trace of one use

02:14:07Z  AssumeRole BreakGlass, DurationSeconds=3600
           userIdentity.arn = arn:aws:sts::111122223333:assumed-role/BreakGlass/INC-4471-alice
           sessionContext.attributes = { incident: INC-4471 }
02:14:09Z  pager fires: "BreakGlass assumed by alice, INC-4471"
02:31:44Z  ec2:TerminateInstances  -> allowed (approval recorded)
03:14:07Z  session expires
03:20:11Z  same hardware key, DescribeInstances -> AccessDenied

The key itself does not expire. What bounds the key is physical: a tamper-evident seal and a sign-out log, checked in the post-incident review.

Trade-offs

Standing privileged account plus MFA versus just-in-time elevation. Standing is simpler and survives an IdP outage; JIT gives attribution and no standing privilege. The deciding criterion is whether your emergency class includes IdP outage, if it does, you need at least one path that never traverses the IdP.

Lighter is right for a five-person team: sealed root credential, hardware MFA, CloudTrail alert to a phone. Heavier is right when operations are irreversible. Dual control is wrong when the second approver is asleep and approves without reading: you have added latency and no control. It earns its cost only where a second person actually inspects the diff.

Keep break-glass out of its own blast radius: separate account, separate vault, and a second alerting channel, because the paging system may be the thing that is down.

Failure modes and detection

  • Credential co-located with the systems it unlocks. One incident takes both. Detect with a vault dependency map.
  • Permission creep. The role accretes rights because it is the "make it work" role. Detect by diffing its policy quarterly against a checked-in baseline and alerting on any change.
  • Alert theatre. The page fires and nobody acknowledges. Detect by tracking acknowledgement latency on break-glass pages specifically, not on pages generally.
  • Shared credential. Two responders using one session name from different IPs. Detect with a CloudTrail query for a session name appearing under distinct sourceIPAddress values.

Afterwards: the session credential is already dead, so rotate anything it touched, reconcile data access for the session window, review that CloudTrail slice, and re-seal the key with a log entry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What should authentication and authorization audit logs contain?

Answer

Assumptions first: multi-tenant SaaS, human users plus workload identities, an IdP issues tokens, and you own the application's audit log, not the IdP's. That matters because the fields you can trust are the ones your service observes, not the ones a token claims.

The 90-second answer: an auth audit event has to answer six questions without ever storing the secret, who acted, as whom, on what, when, from where, under what authority, and did it succeed. If any of those is missing, the log can't support an investigation or an appeal.

Then the fields, and why each earns its place:

  • Timestamp: RFC 3339, UTC, millisecond precision, plus the clock source. Skew across services is what breaks timeline reconstruction, not the format.
  • Event and outcome: a closed enum (auth.login, mfa.challenge, session.revoke, admin.impersonate.start) and a stable reason code (invalid_credential, mfa_timeout, account_locked). Reason codes are what detection rules and user appeals key on; free text breaks both when someone rewords a message.
  • Actor vs effective subject: the authenticated principal and the identity the action lands on. They differ under impersonation and delegation, and this is the field most often dropped. Store opaque IDs (usr_8f3a1c), not emails.
  • Tenant, resource type and a privacy-safe resource ID.
  • Assurance: AAL per NIST SP 800-63B, the method (password, WebAuthn, TOTP), a hashed session identifier, and session age. Freshness is what separates a stolen-then-reused session from a live one.
  • Client/workload: IP, user agent, device ID, or workload identity.
  • Policy version, which config decided the outcome, so you can replay the decision.
  • Correlation ID: the trace ID that joins this auth event to the downstream action.

Example line:

JSON
{
  "ts": "2025-03-11T14:02:07.481Z",
  "event": "auth.login",
  "outcome": "failure",
  "reason": "invalid_credential",
  "actor": "usr_8f3a1c",
  "subject": "usr_8f3a1c",
  "tenant": "org_2291",
  "assurance": {"aal": 2, "method": "webauthn", "session": "sha256:9c1f..."},
  "client": {"ip": "203.0.113.42"},
  "policy_version": "auth-policy-2025.02",
  "trace_id": "b7e2f1a0c9"
}

Never log passwords, recovery codes, TOTP seeds, raw session IDs or bearer tokens. OWASP ASVS 4.0.3 V7.1.1 requires session tokens be stored only in irreversible hashed form (logging moved to V16 in ASVS 5.0). RFC 9336 is the reference model if you want a privacy-preserving schema.

Failure modes, concretely:

  • Drop the effective subject and impersonation becomes unattributable: during an incident you can't answer "which admin acted as this user."
  • Log the raw session token and your log store becomes a credential store; one read-only leak is a full account takeover.
  • Free-text reasons break detection rules on the next deploy, and appeals can't be automated.
  • No correlation ID and you can't join the auth event to the action it authorized.

Trade-offs:

  • Privacy vs debuggability. Full IP and user agent help fraud detection but are personal data under GDPR. Decide by purpose: if you only need coarse geo, truncate to /24.
  • Retention. PCI DSS 4.0 requires 12 months, with 3 months immediately searchable. Longer retention widens breach blast radius; set the floor by regulation and the ceiling by your investigation window.
  • Sync vs async writes. Blocking auth on the log write adds latency and can fail a login; buffering risks loss on crash. Most teams buffer and accept a small loss window.

Detection: alert on reason-code spikes, impossible travel, and MFA fatigue. Many challenges, one success.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How do you test authorization comprehensively?

Answer

First, clarify what authorization means here: the policy decision (allow or deny) and the enforcement of that decision at every entry point. I assume a centralized policy engine such as OPA with Rego, Cedar, or SpiceDB/OpenFGA, and services that call it over HTTP or a sidecar. If there is no central engine, the same matrix applies to whatever code makes the decision.

The core answer is a decision matrix. Rows are (subject, resource, action, context). Columns are expected outcome and the reason. Then I test at three layers: policy unit tests, integration tests through real entry points, and production canaries. The matrix is the source of truth; the layers are how I catch different failures.

Why each dimension breaks authorization:

  • Subject: role, tenant, relationship, and membership state. A user removed from a group but holding a token with the old group claim still passes if the policy trusts the token. Test no identity, expired token, disabled user, and stale membership.
  • Resource: type, owner, tenant, and state. Horizontal ID substitution is the classic: alice changes /docs/1 to /docs/2, where doc 2 belongs to bob. If the policy checks only 'is authenticated' or 'has role editor', it allows. Test deleted resources and draft vs published.
  • Action: read, write, delete, admin. Field-level access is separate: a read allow must not leak salary or ssn. Function-level access: an admin endpoint must not be reachable by a normal user.
  • Context: MFA assurance, IP, time, device. A delete may require step-up MFA even if read does not.

Entry points are where comprehensive testing usually fails. A single GET may enforce the policy, but list, search, and export endpoints often apply filters after fetching. A bulk or nested endpoint may check the top-level object and not each item. GraphQL field resolvers can bypass REST checks. WebSocket connections may authenticate once and never re-check per message. Background jobs often run as a service account with broad rights. I test each of these with the same matrix. For every deny, I assert the audit reason matches the expected rule, not just the status code.

Here is a concrete matrix slice:

subjectresourceactioncontextexpectedwhy
alice@tenantAdoc:1 (tenantA)readvalid tokenallowowner
alice@tenantAdoc:2 (tenantB)readvalid tokendenycross-tenant
alice@tenantAdoc:1readtoken with stale groupdenymembership revoked
admin@tenantAdoc:1deleteno MFAdenystep-up required
alice@tenantAlist /docs?tenant=Breadvalid tokendenylist filter must enforce tenant

A pytest integration test for the first four rows:

Python
import pytest, requests

BASE = 'http://localhost:8080'

@pytest.mark.parametrize('token,path,expected', [
    ('alice-tenantA', '/docs/1', 200),
    ('alice-tenantA', '/docs/2', 403),
    ('alice-tenantA', '/docs?tenant=tenantB', 403),
    ('bob-disabled', '/docs/1', 401),
])
def test_authorization(token, path, expected):
    r = requests.get(BASE + path, headers={'Authorization': f'Bearer {token}'})
    assert r.status_code == expected

Policy unit tests run faster. With OPA you write Rego tests and run opa test; with SpiceDB you use zed to check relationships. These catch logic errors before integration.

Failure modes and detection:

  • Policy cache fails open: after revoking alice, the cache still returns allow for its TTL. Detect with a canary: revoke a test user, immediately request a protected resource, and alert if it returns 200. The unauthorized window equals the cache TTL.
  • Policy bundle version skew: service A runs policy v1, service B runs v2, so the same request gets different decisions. Detect by logging the policy version in every decision and alerting on mismatch across services.
  • Revocation propagation: a JWT remains valid until expiry. Detect by testing that a revoked token gets 401 within the SLO; if not, shorten TTL or add introspection.
  • Cross-tenant race: a request-scoped tenant variable is overwritten by a concurrent request. Detect by running concurrent requests from tenant A and B and asserting no cross-tenant data appears in responses.

Trade-offs: a full matrix is O(subjects × resources × actions × contexts) and explodes. For a small internal service with one role and no multi-tenancy, targeted tests are enough. For multi-tenant regulated data, the matrix is worth it. Policy unit tests are fast and deterministic but miss wiring; integration tests catch enforcement gaps but are slower and flakier. Production canaries catch config drift and real traffic but cannot prove absence. I use unit tests as the gate on every policy change, integration tests on PR, and canaries in production. Rollback is tested by running the same matrix against the previous policy bundle before deploying it. Property-based tests with Hypothesis can assert tenant noninterference: generate random subjects and resources, and assert tenant A never gets allow on tenant B. Differential testing against the previous policy version on recorded decisions catches unintended changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you roll out authorization policy as code safely?

Answer

The 90-second answer. Assume the policy engine is centralized (OPA/Rego, Cedar, or a relationship store like SpiceDB/OpenFGA) that every decision is logged with the policy revision that produced it, and that policy ships as a versioned bundle rather than a hand-edit in a console. Then the safe rollout is test → shadow → canary → enforce, with the revision stamped on every decision. The thing that makes it safe isn't the stage list; it's being able to answer "which decisions did revision 41 make, and what should they have been?"

Why shadow catches what tests miss. Unit tests run on fixtures you wrote, so they cover the cases you thought of. Shadow evaluates the new policy on the same input as the old one, in the same request, and logs both results. Production input distribution is not your fixture set: nested group membership, resources with no owner, tenants with 10x the average relationship count. Concretely: fixtures grant viewer on doc:1; in prod 4% of documents are owned by a group nested two levels deep, and the new group-expansion rule is wrong there. opa test passes; shadow shows 1,200 of 30,000 sampled decisions flip from deny to allow, all on one resource type. That's the signal, and it's the one tests structurally cannot give you.

Cost: you evaluate twice, so CPU per authz request roughly doubles during shadow. On an in-process OPA at ~1 ms p99 that's fine; on a remote PDP at 8 ms p99 you shadow a sample instead of everything.

Bounding the faulty window. Decision logs carry decision_id, bundle revision, timestamp, and the input:

JSON
{"decision_id":"d_9f2","bundle_revision":"41","timestamp":"2024-05-02T10:14:03Z",
 "input":{"user":"u_88","action":"read","resource":"doc:1"},"result":{"allow":true}}
Shell
# which resource types did revision 41 newly allow?
jq -r 'select(.bundle_revision=="41" and .result.allow) | .input.resource | split(":")[0]' \
  decisions-*.jsonl | sort | uniq -c | sort -rn

After a rollback the faulty window is [first deploy of the bad revision, rollback]. Replay the logged inputs in that window through the restored bundle and diff. If you log 100% of decisions the window is exact; if you sample at 1%, you can only bound it probabilistically: say that in the incident rather than claiming completeness.

Choosing between shadow, canary and staged enforcement. The deciding criterion is the blast radius of a wrong allow versus a wrong deny.

stagecatchescostsuse when
shadowdata-dependent flips, wrong group expansion2x eval CPUalways, before any enforcement
canary (5% of traffic, or one tenant)engine failures, latency, cache bugsreal users get wrong decisionsthe change widens the allow set
staged enforcement—slowa wrong deny is an outage (write paths)

Enforcement-at-merge is acceptable when the change only narrows access, the tests are generated from the same source of truth as the policy, and deny is fail-safe.

Failure modes and how you detect them.

  • Stale cache after rollback. If the PDP caches decisions keyed by (subject, resource, action) without the bundle revision, allows from the bad revision survive the rollback. Detect: cache hit rate doesn't dip after deploy and decision logs still show revision 41. Fix: put the revision in the cache key. A 30 s TTL bounds staleness, but at 50k rps that's 50k recomputes per TTL window.
  • Partial rollout. Some PDP replicas on revision 41, some on 42: same request, different answers. Detect: histogram bundle_revision in decision logs during rollout; a bimodal distribution means the rollout isn't finished.
  • Policy/data skew. The policy references a relationship type the backfill hasn't populated. Detect: shadow diffs concentrated on one resource type rather than spread across tenants.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design identity and access management for a multi-tenant SaaS platform.

Answer

Assumptions I'd state up front: B2B SaaS where a tenant is a customer org; one user can belong to several tenants with different roles; enterprise tenants require SSO (SAML 2.0 or OIDC) and SCIM 2.0 provisioning; some tenants hold regulated data. Scale: ~10k tenants, ~1M users, p99 authorization decision budget 10 ms.

Core answer. Split identity from authorization. Users authenticate against our OIDC provider, or, for enterprise tenants, against their own IdP via SAML 2.0/OIDC federation, with SCIM 2.0 pushing create/update/deactivate. Never model a user as owning data; model membership: a tuple (user, tenant, role). Authorization is deny-by-default and evaluated as a function of (subject, action, resource, tenant, context).

I'd use relationship-based access control (Zanzibar-style tuples, e.g. OpenFGA) for resources with sharing semantics (documents, projects) and coarse RBAC roles for tenant administration. ReBAC answers "can this user see this doc" without enumerating roles; RBAC is far cheaper to reason about for a fixed admin surface. Don't force one model everywhere.

Tokens: access tokens are JWTs with a 10-minute TTL, audience- and scope-scoped to one service; refresh tokens rotate on every use with reuse detection. Workloads get their own identity (SPIFFE/mTLS or cloud workload identity), never a shared service account.

Tenant isolation: tenant_id is a required claim and a required column; Postgres row-level security enforces it so a missing WHERE clause can't leak.

Trade-offs. Centralized PDP (OPA/Rego, Cedar) vs embedded library: centralized gives one policy language, one audit trail, hot reload. At the cost of a network hop and a new SPOF, mitigated with a local sidecar and a cached decision bundle. Embedded is faster but drifts across services. Stateless JWT vs opaque tokens: JWT avoids per-request introspection but revocation is bounded by TTL; opaque tokens revoke instantly but cost a lookup per call.

Failure modes.

  • Revocation lag: a fired employee keeps access until the JWT expires. Detect by alerting when deprovision-to-last-successful-use exceeds TTL. Mitigate with the 10-min TTL plus a revocation list keyed by token version, checked at the gateway.
  • Cross-tenant leak: a query missing tenant_id. Detect with RLS plus a canary tenant whose rows must never appear in another tenant's response.
  • SCIM deprovision race: the IdP deactivates a user but an in-flight session refreshes. Bind refresh to a session record that SCIM deactivation revokes.
  • Stale policy cache: a grant doesn't take effect. Version policy bundles, cache decisions for 30 s, bump the version to force invalidation.

Worked trace: "can user U read doc D in tenant T?" with these tuples:

doc:D#viewer@group:eng#member
group:eng#member@user:U
doc:D#parent@folder:F
folder:F#viewer@tenant:T#member

Resolve doc:D#viewer: it includes group:eng#member; is U a member of eng? Yes → allow. Had doc:D only carried folder:F#viewer@tenant:T#member, U would need membership in tenant T instead: the same check, one hop further.

Arithmetic on the revocation window. 10-min TTL, 1M users, 5% daily churn → 50k deprovisions/day, worst-case 10 min of exposure each. To get under 60 s you either drop the TTL to 60 s (≈10× refresh traffic) or add the version check: that's the decision, not a preference.

Curated: · Written: · Reviewed:

Difficulty: Hard