Authentication and authorization
Who is calling and what may they do: password storage and MFA, sessions against tokens, OAuth 2.0 and OpenID Connect, JWT validation attacks shown in C#, RBAC and relationship-based permissions, tenant isolation and service identity.
ConceptApplied27 min readUpdated
- 1 sequence flow
- 6 code samples
- 7 interviewer follow-ups
- 5 self-checks
On this page11 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, API design
- Separate authentication from authorization, and say where each is enforced.
- Store passwords with a salted, slow, versioned hash, and describe MFA, passkeys and the defences against credential stuffing.
- Compare sessions and tokens, and walk through OAuth 2.0 authorization code with PKCE and OpenID Connect.
- Validate a token correctly by pinning the algorithm and key and checking issuer, audience and expiry, and explain the none and algorithm-confusion attacks.
- Model permissions as roles, attributes or relationships, check access to each object on every request, and isolate tenants.
6 code samples (222 lines), collapsed so the explanation stays in focus.
A system design answer that ends at "and users log in" has skipped half of what a staff engineer is paid to think about. Authentication answers who is calling. Authorization answers what they may do, and it is the harder one, because it has to be right for every object on every request, for years, while the product adds sharing, teams, tenants and partners. The failures here are not exotic. They are a token that is not validated, an object id that is not checked, and a role model that cannot express "can edit this folder but not that one". This lesson covers both, with the parts that interviews ask about built and attacked in C#.
Before choosing mechanisms, say what you are protecting and from whom. Draw the trust boundaries on your diagram (the internet and your edge, your edge and your services, one tenant and another, your services and a vendor) and ask at each one: who can call this, what can they send, what can they read, and what happens if they lie? STRIDE is a checklist for the questions.
| Threat | Means | Typical defence |
|---|---|---|
| Spoofing | Pretending to be someone else | Strong authentication, MFA, mutual TLS between services |
| Tampering | Changing data in transit or at rest | TLS, signatures, authenticated encryption, integrity checks |
| Repudiation | "I never did that" | Audit logs that cannot be edited by the actor |
| Information disclosure | Reading what you should not | Authorization on every object, encryption, least privilege |
| Denial of service | Making it unavailable or expensive | Rate limits, quotas, a CDN, load shedding |
| Elevation of privilege | Becoming more powerful than granted | Deny by default, least privilege, input validation, isolation |
Principles that settle most arguments: least privilege (every identity gets the minimum it needs), deny by default (no rule means no access), defence in depth (a second control behind the first), complete mediation (check every access, never only the first), fail closed, and never trust the client, because everything the client sends can be forged.
Passwords. The database will leak one day, so what is stored must be useless to the thief. Store a salted, deliberately slow hash, never the password and never a fast hash such as SHA-256 on its own. The salt is random and per password, so equal passwords look different and precomputed tables are useless. The slowness is the point: a fast hash lets an attacker with a stolen table try billions of guesses a second, and a hash that takes 150 ms makes each guess cost that. Use Argon2id where you can, otherwise scrypt, bcrypt or PBKDF2 (the OWASP guidance for PBKDF2 with HMAC-SHA256 is 600,000 iterations). Store the parameters with the hash, so that you can raise them and re-hash each user at their next login. The sample does exactly that.
C# · Password storage: a random salt per password, a deliberately slow function, and the…
using System;
using System.Security.Cryptography;
using System.Text;
// Password storage: a random salt per password, a deliberately slow function, and the parameters stored with the hash so that they can
// be raised later. The format is "pbkdf2-sha256$iterations$salt$hash".
public static class Passwords
{
public const int CurrentIterations = 600_000;
public static string Hash(string password, int iterations = CurrentIterations)
{
var salt = RandomNumberGenerator.GetBytes(16);
var hash = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA256, 32);
return $"pbkdf2-sha256${iterations}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";
}
// Returns whether the password matches, and whether the stored hash should be replaced because it uses old parameters.
public static (bool Valid, bool NeedsRehash) Verify(string password, string stored)
{
var parts = stored.Split('$');
if (parts.Length != 4 || parts[0] != "pbkdf2-sha256") return (false, false);
int iterations = int.Parse(parts[1]);
var salt = Convert.FromBase64String(parts[2]);
var expected = Convert.FromBase64String(parts[3]);
var actual = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA256, expected.Length);
return (CryptographicOperations.FixedTimeEquals(actual, expected), iterations < CurrentIterations); // constant-time comparison
}
}C#
using System;
using System.Diagnostics;
string first = Passwords.Hash("correct horse battery staple");
string second = Passwords.Hash("correct horse battery staple");
Debug.Assert(first != second); // a fresh random salt each time, so equal passwords look different
Debug.Assert(Passwords.Verify("correct horse battery staple", first) == (true, false));
Debug.Assert(Passwords.Verify("Correct horse battery staple", first) == (false, false));
string legacy = Passwords.Hash("hunter2", 10_000); // an old hash with weak parameters
var (valid, rehash) = Passwords.Verify("hunter2", legacy);
Debug.Assert(valid && rehash); // accepted, and the login flow should store a new hash now
Debug.Assert(Passwords.Verify("anything", "not-a-hash") == (false, false));Around the hash: allow long passphrases and check new passwords against known-breached lists, which beats composition rules. Rate-limit login attempts by account, by address and by device (see rate limiting), because the common attack is credential stuffing: leaked email and password pairs from other sites replayed against yours, which succeeds because people reuse passwords. Treat the password reset flow as a second front door: single-use, short-lived tokens, a response that does not reveal whether the account exists, and a notification to the owner.
MFA and passkeys. A second factor turns a stolen password into a failed attack. Codes from an authenticator app (TOTP) are good, push approvals are good until people approve by reflex, and SMS is the weakest because of SIM swapping (and, as the notification lesson shows, a target for fraud). Passkeys (WebAuthn) replace the password with a key pair on the user's device: the server stores a public key, the device signs a challenge that is bound to your site's origin, and a look-alike phishing site gets nothing it can use. They are the strongest option and the direction the industry is moving.
Sessions or tokens. After login the client needs something to present on every request.
| Server-side session | Self-contained token (JWT) | |
|---|---|---|
| What the client holds | A random session id in a cookie | A signed token with the identity and claims inside |
| What the server stores | The session, in memory or a shared store | Nothing: it validates the signature |
| Revocation | Delete the session: immediate | Hard: the token is valid until it expires, unless you keep a denylist |
| Cost per request | A lookup | A signature check |
| Best for | Browser apps, where immediate logout and revocation matter | APIs and service-to-service calls, where the lookup is what you are avoiding |
Tokens stay short-lived (minutes) so that revocation is rarely needed, and a refresh token, which can be revoked and is rotated on every use, gets new ones. For browsers, a session or token in a cookie marked HttpOnly (scripts cannot read it, which limits what an XSS bug can steal), Secure (HTTPS only) and SameSite (not sent on cross-site requests, which blunts CSRF) is safer than one in localStorage, which any injected script can read.
OAuth 2.0 and OpenID Connect. When a user lets one application act on their behalf at another (log in with Google, connect a calendar), nobody should type a password into the wrong place. OAuth 2.0 is a delegation framework: the user signs in at the authorization server, which gives the client application a token with limited scopes, to present to the resource server (the API). OAuth alone says nothing about who the user is, so OpenID Connect adds an ID token, a signed statement of identity, which is what "log in with" uses. The flow for browsers and mobile apps is the authorization code flow with PKCE.
The code comes back through the browser, where something could read it, so the app proves it is the one that started the flow by sending the original code_verifier when it redeems the code, and the server checks that its hash matches the code_challenge from the start (PKCE). The state value ties the response to the request and stops cross-site forgery. The older flows are deprecated: the implicit flow, which put tokens in URLs, and the password grant, which handed the user's password to the client. Between services with no user, the client credentials grant gets a token for the service itself. Common mistakes are an unchecked redirect_uri (an open redirect hands out codes), no state, tokens in query strings (they end up in logs) and treating an access token as proof of identity.
A JSON Web Token is three base64url parts, header.payload.signature, where the signature covers the first two. The payload carries claims: iss (who issued it), aud (who it is for), sub (the subject), exp (expiry), nbf (not before) and others. It is signed, not encrypted: anyone can read it, so no secrets go in it. A verifier has to do four things, and each omission is a known attack.
- Choose the algorithm and the key itself. Never let the token say how it should be verified.
- Verify the signature over the exact bytes, and compare in constant time.
- Check the claims: the issuer is the one you trust, the audience is this service, and the token has not expired (allowing a few seconds of clock skew).
- Handle keys properly: fetch the issuer's public keys from its published key set, pick by the
kidheader, cache them with a TTL, and tolerate rotation.
The sample implements both a naive and a strict verifier for RS256 tokens (RSA signatures, verified with a public key) and attacks them. The naive one reads the algorithm from the token. The attacks are the two classics from the JWT best-practice RFC: alg: none, a token with no signature at all, and algorithm confusion, where the attacker takes the issuer's public key (it is public), signs a token with HS256 (an HMAC) using the key's bytes as the shared secret, and sends it. A verifier that obeys the header and was handed the public key as "the key" computes the same HMAC and accepts the forgery.
C# · Verdict, Jwt
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
public sealed record Verdict(bool Valid, string Reason);
// A JSON Web Token is three base64url parts: header.payload.signature. The signature covers the first two.
public static class Jwt
{
public static string B64(byte[] data) => Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
public static byte[] FromB64(string text)
{
string s = text.Replace('-', '+').Replace('_', '/');
return Convert.FromBase64String(s.PadRight(s.Length + (4 - s.Length % 4) % 4, '='));
}
public static string SignHs256(string payloadJson, byte[] secret)
{
string signingInput = B64(Encoding.UTF8.GetBytes("{\"alg\":\"HS256\",\"typ\":\"JWT\"}")) + "." + B64(Encoding.UTF8.GetBytes(payloadJson));
return signingInput + "." + B64(HMACSHA256.HashData(secret, Encoding.UTF8.GetBytes(signingInput)));
}
public static string SignRs256(string payloadJson, RSA privateKey)
{
string signingInput = B64(Encoding.UTF8.GetBytes("{\"alg\":\"RS256\",\"typ\":\"JWT\"}")) + "." + B64(Encoding.UTF8.GetBytes(payloadJson));
return signingInput + "." + B64(privateKey.SignData(Encoding.UTF8.GetBytes(signingInput), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
}
// The mistake: let the token say how it should be verified. An attacker who knows the public key (it is public) signs a token with
// HS256 using the public key's bytes as the secret, and this verifier, configured with that key for RS256, computes the same HMAC.
public static Verdict VerifyNaive(string token, RSA publicKey, byte[] publicKeyBytes)
{
var parts = token.Split('.');
if (parts.Length != 3) return new Verdict(false, "malformed");
string alg = JsonDocument.Parse(FromB64(parts[0])).RootElement.GetProperty("alg").GetString();
byte[] signed = Encoding.UTF8.GetBytes(parts[0] + "." + parts[1]);
byte[] signature = FromB64(parts[2]);
if (alg == "none") return new Verdict(true, "alg none accepted");
if (alg == "HS256") return new Verdict(CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(publicKeyBytes, signed), signature), "hs256 with the public key");
if (alg == "RS256") return new Verdict(publicKey.VerifyData(signed, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1), "rs256");
return new Verdict(false, "unsupported algorithm");
}
// The fix: the verifier fixes the algorithm and the key, and checks the claims that make a token mean something here.
public static Verdict VerifyStrict(string token, RSA publicKey, string issuer, string audience, long now, int skewSeconds)
{
var parts = token.Split('.');
if (parts.Length != 3) return new Verdict(false, "malformed");
string alg = JsonDocument.Parse(FromB64(parts[0])).RootElement.GetProperty("alg").GetString();
if (alg != "RS256") return new Verdict(false, "unexpected algorithm " + alg); // never choose the algorithm from the token
byte[] signed = Encoding.UTF8.GetBytes(parts[0] + "." + parts[1]);
if (!publicKey.VerifyData(signed, FromB64(parts[2]), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) return new Verdict(false, "bad signature");
var claims = JsonDocument.Parse(FromB64(parts[1])).RootElement;
if (claims.GetProperty("iss").GetString() != issuer) return new Verdict(false, "wrong issuer");
if (claims.GetProperty("aud").GetString() != audience) return new Verdict(false, "wrong audience");
if (now > claims.GetProperty("exp").GetInt64() + skewSeconds) return new Verdict(false, "expired");
if (claims.TryGetProperty("nbf", out var nbf) && now < nbf.GetInt64() - skewSeconds) return new Verdict(false, "not yet valid");
return new Verdict(true, "ok");
}
}C#
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using var rsa = RSA.Create(2048);
byte[] publicBytes = rsa.ExportSubjectPublicKeyInfo();
using var publicOnly = RSA.Create();
publicOnly.ImportSubjectPublicKeyInfo(publicBytes, out _);
long now = 1_700_000_000;
const string Issuer = "https://login.example.com", Audience = "orders-api";
string claims = "{\"iss\":\"" + Issuer + "\",\"aud\":\"" + Audience + "\",\"sub\":\"user-17\",\"exp\":" + (now + 600) + "}";
string good = Jwt.SignRs256(claims, rsa);
Debug.Assert(Jwt.VerifyStrict(good, publicOnly, Issuer, Audience, now, 30).Valid);
// A payload changed after signing: the signature no longer matches, for both verifiers.
var parts = good.Split('.');
string tampered = parts[0] + "." + Jwt.B64(Encoding.UTF8.GetBytes(claims.Replace("user-17", "admin"))) + "." + parts[2];
Debug.Assert(!Jwt.VerifyNaive(tampered, publicOnly, publicBytes).Valid);
Debug.Assert(Jwt.VerifyStrict(tampered, publicOnly, Issuer, Audience, now, 30).Reason == "bad signature");
// alg none: a token with no signature at all.
string none = Jwt.B64(Encoding.UTF8.GetBytes("{\"alg\":\"none\"}")) + "." + Jwt.B64(Encoding.UTF8.GetBytes(claims.Replace("user-17", "admin"))) + ".";
Debug.Assert(Jwt.VerifyNaive(none, publicOnly, publicBytes).Valid); // the naive verifier accepts a forged admin token
Debug.Assert(Jwt.VerifyStrict(none, publicOnly, Issuer, Audience, now, 30).Reason == "unexpected algorithm none");
// Algorithm confusion: HS256, signed with the public key's bytes as the secret.
string forged = Jwt.SignHs256(claims.Replace("user-17", "admin"), publicBytes);
Debug.Assert(Jwt.VerifyNaive(forged, publicOnly, publicBytes).Valid); // accepted: the attacker needed only the public key
Debug.Assert(Jwt.VerifyStrict(forged, publicOnly, Issuer, Audience, now, 30).Reason == "unexpected algorithm HS256");
// The claims that make a genuine token mean something here.
Debug.Assert(Jwt.VerifyStrict(good, publicOnly, Issuer, "billing-api", now, 30).Reason == "wrong audience"); // a token for another service
Debug.Assert(Jwt.VerifyStrict(good, publicOnly, "https://evil.example.com", Audience, now, 30).Reason == "wrong issuer");
Debug.Assert(Jwt.VerifyStrict(good, publicOnly, Issuer, Audience, now + 700, 30).Reason == "expired");
Debug.Assert(Jwt.VerifyStrict(good, publicOnly, Issuer, Audience, now + 620, 30).Valid); // 20 seconds past expiry, inside the skew| Token | Naive verifier (algorithm from the header) | Strict verifier (algorithm and key fixed) |
|---|---|---|
| A genuine token | Accepted | Accepted |
| Payload changed after signing | Rejected | Rejected: bad signature |
alg: none, no signature | Accepted | Rejected |
| HS256 signed with the public key (algorithm confusion) | Accepted | Rejected |
| Genuine token for another service | Accepted, since it checks no claims | Rejected: wrong audience |
| Expired a minute ago | Accepted | Rejected, though 20 seconds past is inside the skew |
The two accepted forgeries needed no secret: an attacker who can read a public key can mint administrator tokens against the naive verifier. The audience check is the quietest of the four: a token issued for the billing API is a perfectly genuine token, and a service that does not check aud will accept it, which lets one compromised low-value service replay its tokens against high-value ones. Libraries implement all of this, and the job is to configure them strictly (an explicit algorithm list, an explicit issuer and audience) and not to leave the defaults.
Authentication ends at "this is user 17". Authorization is a function from (caller, action, object) to allowed or denied, and the first mistake is evaluating it at the edge only. Broken object level authorization (BOLA, also called IDOR) is the first entry in the OWASP API Security list for a reason: the API checks that the caller is logged in and then returns whatever object id was in the URL, so changing /orders/1001 to /orders/1002 shows someone else's order. An opaque id is not authorization. Every access to every object must check that this caller may do this thing to this object, on the server, in the service that owns the data.
| Model | A permission is | Strength | Where it strains |
|---|---|---|---|
| RBAC, role-based | A user has roles, and roles have permissions (admin, editor) | Simple, auditable, familiar | "Editor of this folder but not that one" multiplies the roles |
| ABAC, attribute-based | A policy over attributes of the user, the object and the context (department, owner, time, location) | Expressive, central policy | Hard to answer "who can see this?", and policies get complicated |
| ReBAC, relationship-based | A chain of relationships between the user and the object (member of a group that is a viewer of the parent folder) | Natural for sharing, nesting and inheritance | Needs a purpose-built store, and checks walk a graph |
Products with sharing (documents, repositories, workspaces) end up with relationships whether they plan for it or not. Google's Zanzibar system made this explicit: permissions are stored as relation tuples (doc:plan#viewer@user:alice, "alice is a viewer of the plan") and a check asks whether a user has a relation to an object, following group membership, relation hierarchy (an editor is also a viewer) and inheritance (the viewers of a folder can view what is in it). Open-source systems in the same family include OpenFGA and SpiceDB, and policy engines such as Open Policy Agent and Cedar cover the attribute-based end. The sample is a small Zanzibar-style engine with groups that contain groups, nested folders and cycle protection.
C# · A relationship tuple in the style of Google's Zanzibar: "object#relation@subject". The…
using System;
using System.Collections.Generic;
using System.Linq;
// A relationship tuple in the style of Google's Zanzibar: "object#relation@subject". The subject is a user (user:alice) or a set of
// users named by another relation (group:eng#member means every member of group:eng).
public sealed class Permissions
{
// The tuple store, indexed by (object, relation): the subjects related to that object in that way.
private readonly Dictionary<(string Object, string Relation), List<string>> subjects = new Dictionary<(string, string), List<string>>();
public int TupleCount => subjects.Values.Sum(s => s.Count);
public long TuplesRead; // work counter
public void Write(string obj, string relation, string subject)
{
if (!subjects.TryGetValue((obj, relation), out var list)) subjects[(obj, relation)] = list = new List<string>();
list.Add(subject);
}
public void Delete(string obj, string relation, string subject)
{
if (subjects.TryGetValue((obj, relation), out var list)) list.Remove(subject);
}
private IEnumerable<string> Read(string obj, string relation)
{
if (!subjects.TryGetValue((obj, relation), out var list)) yield break;
foreach (var subject in list.ToArray())
{
TuplesRead++;
yield return subject;
}
}
// What a relation includes: an "editor" is also a "viewer", and an "owner" is also an "editor".
private static readonly Dictionary<string, string> Stronger = new Dictionary<string, string> { ["viewer"] = "editor", ["editor"] = "owner" };
// Is `user` related to `obj` by `relation`? True if there is a direct tuple, a tuple naming a set the user belongs to ("group:eng#member"),
// a stronger relation that implies it, or the same relation on a parent of the object. `visiting` stops cycles.
public bool Check(string obj, string relation, string user, HashSet<(string, string)> visiting = null)
{
visiting ??= new HashSet<(string, string)>();
if (!visiting.Add((obj, relation))) return false;
foreach (string subject in Read(obj, relation))
{
if (subject == user) return true;
int hash = subject.IndexOf('#');
if (hash > 0 && Check(subject.Substring(0, hash), subject.Substring(hash + 1), user, visiting)) return true;
}
if (Stronger.TryGetValue(relation, out var stronger) && Check(obj, stronger, user, visiting)) return true;
if (relation != "parent")
foreach (string parent in Read(obj, "parent"))
if (Check(parent, relation, user, visiting)) return true;
return false;
}
}C#
using System;
using System.Diagnostics;
var permissions = new Permissions();
permissions.Write("folder:eng", "owner", "user:alice");
permissions.Write("folder:eng", "viewer", "group:eng#member");
permissions.Write("group:eng", "member", "user:bob");
permissions.Write("group:eng", "member", "group:platform#member"); // groups can contain groups
permissions.Write("group:platform", "member", "user:dana");
permissions.Write("folder:eng-2026", "parent", "folder:eng"); // folders nest
for (int i = 0; i < 1_000; i++) permissions.Write("doc:" + i, "parent", "folder:eng-2026");
permissions.Write("doc:7", "editor", "user:erin"); // a direct grant on one document
Debug.Assert(permissions.TupleCount == 1_007); // 1,000 documents, and access to all of them takes six tuples
Debug.Assert(permissions.Check("doc:1", "editor", "user:alice")); // the owner of the top folder edits everything inside it
Debug.Assert(permissions.Check("doc:1", "viewer", "user:bob") && !permissions.Check("doc:1", "editor", "user:bob")); // a group viewer cannot edit
Debug.Assert(permissions.Check("doc:999", "viewer", "user:dana")); // through a group inside a group, and a folder inside a folder
Debug.Assert(permissions.Check("doc:7", "viewer", "user:erin") && !permissions.Check("doc:8", "viewer", "user:erin")); // a direct grant stays on its document
Debug.Assert(!permissions.Check("doc:1", "viewer", "user:carol")); // no relationship: denied by default
permissions.Delete("group:eng", "member", "user:bob"); // one write revokes bob's access to every document at once
Debug.Assert(!permissions.Check("doc:1", "viewer", "user:bob") && !permissions.Check("doc:999", "viewer", "user:bob"));
permissions.Write("folder:a", "parent", "folder:b");
permissions.Write("folder:b", "parent", "folder:a");
Debug.Assert(!permissions.Check("folder:a", "viewer", "user:alice")); // a cycle terminates, and denies
Debug.Assert(permissions.TuplesRead < 100); // a dozen checks read well under a hundred tuplesSix tuples gave a group and an owner access to a thousand documents, and one delete revoked a user from all of them: with a per-document access list the same change is a thousand writes, and the thousand-and-first document needs its own entry. That is the case for relationships. Their costs are the check (a graph walk, so it needs an index on the tuples and caching, and very deep group nesting needs precomputed indexes of its own) and consistency. Zanzibar names the trap the new enemy problem: Alice removes Bob from a folder and then adds a sensitive document to it, and if Bob's check is answered from a stale cache or replica he can see it. Its answer is a token (a "zookie") that a write returns and a later check presents, which forces the check to be at least as fresh as that write. Any design that caches permissions needs a position on exactly this: how stale may a grant or a revocation be?
Multi-tenancy means many customers share the system, and the worst bug is one customer's data reaching another. The defence is structural. Carry the tenant id in the identity, put it on every row, and make every query carry it, enforced where it cannot be forgotten: a data-access layer that adds the filter, or the database's own row-level security. There is a spectrum of isolation: a shared schema (cheap, one bad query leaks), a schema or database per tenant (stronger, costs operations at 10,000 tenants), and a whole stack per tenant for the largest or most regulated. Quotas and rate limits per tenant stop a noisy neighbour, and cross-tenant access gets its own automated tests that create two tenants and try every endpoint across the boundary.
Services need identities too. Inside the network, "it came from an internal address" proves nothing once one host is compromised, so services authenticate each other, usually with mutual TLS (each side presents a certificate) or signed tokens from a workload identity system (SPIFFE is the standard for the identity document), with credentials that are short-lived and issued automatically. Authorize between services as well: the checkout service may call payments, the recommendation service may not. And carry the end user's identity through the chain (an on-behalf-of token), because a service that acts for a user using only its own powerful identity becomes a confused deputy: any user can trick it into doing what only the service could.
| Failure | What goes wrong | Defence |
|---|---|---|
| BOLA or IDOR | /orders/1002 shows another user's order | Authorize every object access on the server, by owner or relationship, and test it with a second user |
| A token the service did not validate | Forged or foreign tokens accepted: alg: none, algorithm confusion, wrong audience | Fixed algorithm and key, issuer and audience checks, an explicit allow-list in the library |
| Credential stuffing | Reused passwords from other breaches log attackers in | MFA or passkeys, breached-password checks, rate limits by account, address and device |
| A fast hash for passwords | A stolen table is cracked in hours | Salted, slow, versioned hashes, and re-hash at login |
| Long-lived tokens and no revocation | A stolen token works for days | Short access tokens, rotating refresh tokens, a denylist or introspection for sensitive actions |
| Stale permission caches | Revoked access keeps working, the new enemy problem | Bounded staleness, consistency tokens on sensitive paths, invalidate on revoke |
| Role explosion | Hundreds of roles that nobody understands | Move to relationships or attributes, review roles periodically |
| A confused deputy | A service acts with its own power for any caller | Propagate the end user's identity, authorize at the resource |
| Tenant leakage | A missing filter shows tenant B's rows to tenant A | Tenant id enforced in the data layer or by row-level security, cross-tenant tests |
| An open redirect in OAuth | Authorization codes are sent to an attacker | Exact-match registered redirect URIs, state, PKCE |
Interviewer follow-upL5What is the difference between authentication and authorization, and where is each enforced?How to answer
Authentication establishes who the caller is (a password, a passkey, a token). Authorization decides what that caller may do with a given object. Authentication happens once per session or token, at the edge or the identity provider. Authorization must be enforced on every access, in the service that owns the data, because the edge cannot know which orders belong to whom. Mention the failure when it is skipped: BOLA.
Interviewer follow-upL5How do you store passwords?How to answer
A random per-password salt and a slow, memory- or CPU-hard function (Argon2id, scrypt, bcrypt or PBKDF2 with a high iteration count), with the parameters stored next to the hash so they can be raised and users re-hashed at their next login, compared in constant time. Never encrypt them, never use a fast hash alone. Around it: breached-password checks, rate-limited login and MFA or passkeys.
Interviewer follow-upL6Sessions or JWTs?How to answer
Server-side sessions revoke instantly and cost a lookup, which suits browser applications. Self-contained tokens need no lookup and scale across services but cannot be revoked until they expire, so they must be short-lived with rotating refresh tokens, and a denylist or introspection for the sensitive operations. Many systems use sessions at the edge and short tokens between services. Whichever you pick, put them in HttpOnly, Secure, SameSite cookies in browsers.
Interviewer follow-upL6How do you validate a JWT correctly, and what attacks target it?How to answer
Fix the algorithm and the key in the verifier and never take them from the token, verify the signature in constant time, and check the issuer, the audience and the expiry with a small skew, picking keys by kid from the issuer's key set. The test showed what happens otherwise: a verifier that obeys the header accepted alg: none and an HS256 token signed with the public key, and one that skips aud accepted a genuine token meant for another service. JWTs are signed and not encrypted, so keep secrets out of them.
Interviewer follow-upL6Design the permissions for a collaborative documents product.How to answer
Relationship-based: tuples such as document, folder and group relations with a hierarchy (owner, editor, viewer), group membership that can nest, and folder inheritance, checked by a Zanzibar-style service with an index on tuples and caching. Sharing a folder with a group is one tuple (six tuples gave access to a thousand documents in the test), and revoking is one delete. Decide the staleness you can tolerate and use consistency tokens on writes that must be seen at once, so the new enemy problem cannot expose a document added after a revoke.
Interviewer follow-upL7How do you revoke access immediately when tokens are stateless and permissions are cached?How to answer
Make the window small and the sensitive paths strict. Short access tokens (minutes) with rotating refresh tokens that can be revoked, so a revoke takes effect at the next refresh. A denylist of token ids, or introspection, for sensitive operations. Push invalidation to permission caches on revoke, and use consistency tokens so a check after a revoke is never answered from before it. Account for the long-lived paths too: WebSockets and background jobs must re-check authorization when they act and not only when they start.
Interviewer follow-upL7Design tenant isolation for a B2B SaaS with 10,000 tenants, a few of them huge.How to answer
Shared infrastructure with the tenant id in every identity, row and query, enforced by a data-access layer or row-level security, so isolation does not depend on each developer remembering a filter. Per-tenant quotas and rate limits against noisy neighbours, per-tenant encryption keys where customers require them, tenant-aware sharding so that a giant tenant gets its own shard or cell, and an upgrade path to dedicated stacks for the biggest or most regulated customers. Automate tests that try to cross tenant boundaries on every endpoint, and make the tenant part of the audit log.
Say who the actors are and where the trust boundaries sit, then the mechanisms in order. Users log in with passkeys or a salted slow hash plus MFA, with rate limits against credential stuffing. Browsers get a short session in an HttpOnly cookie, or OAuth with PKCE for third-party access. Services validate tokens strictly (fixed algorithm and key, issuer, audience, expiry) and talk to each other over mutual TLS with workload identities. Authorization is checked on every object in the owning service, with relationships for sharing, deny by default, and revocation designed in. Tenants are isolated in the data layer. End with what you would log and alert on.
Authentication establishes who is calling and authorization decides what they may do with this object, on the server, for every access, with deny by default and BOLA as the failure to name. Passwords are stored with a per-password salt and a slow, versioned hash that is compared in constant time, in front of MFA or passkeys and rate limits against credential stuffing. Sessions revoke instantly at a lookup's cost, while tokens are stateless and need short lifetimes and refresh rotation. OAuth 2.0 with PKCE delegates access safely and OpenID Connect adds identity. A JWT verifier must fix the algorithm and key and check issuer, audience and expiry: the naive verifier in the test accepted alg: none and an HS256 token signed with the public key, and ignored audience, while the strict one rejected all three. Permissions as roles strain under sharing, and relationship tuples with groups, hierarchy and inheritance gave access to 1,000 documents with six tuples and revoked a user with one delete, at the price of a graph walk and a position on how stale a cache may be (the new enemy problem). Tenant ids are enforced in the data layer, services authenticate each other with short-lived identities, and the end user's identity travels with the request.
Try answering out loud before you reveal each answer.
QuestionWhy do passwords need a per-password salt and a slow hash, and what do you store with the hash?Reveal answer
The salt makes equal passwords look different and defeats precomputed tables, and the slow hash makes each guess expensive (150 ms with 600,000 iterations, against billions a second for a fast hash). Store the algorithm and its parameters with the hash so you can raise them: the test accepted an old 10,000-iteration hash and flagged it for re-hashing at the user's next login.
QuestionA token's header says alg: HS256, but your service verifies RS256 tokens with the issuer's public key. What should the verifier do, and what attack is this?Reveal answer
Reject it, because the verifier fixes the algorithm and the key itself and never lets the token choose. The attack is algorithm confusion: the attacker signs an HS256 token using the public key's bytes as the secret, and a verifier that follows the header computes the same HMAC and accepts it. In the test the naive verifier accepted it and the strict one answered "unexpected algorithm HS256".
QuestionAlice owns a folder, Bob is in a group that has viewer access to it, and a document is inside a subfolder. What can each do with the document, and what does removing Bob from the group change?Reveal answer
Alice can edit it (the folder's owner is also an editor and a viewer, and relations are inherited down the folders), and Bob can view it but not edit it. Removing Bob from the group is a single deletion and revokes his access to every document under the folder at once, where per-document access lists would need a write for each document.
QuestionAn API returns an order for any valid id in the URL, once the caller is logged in. What is wrong, and how do you test for it?Reveal answer
It authenticates and does not authorize the object (BOLA, also called IDOR): changing the id shows someone else's order. Check on the server, in the service that owns the order, that this caller owns it or is related to it. Test with two users: create an object as one and try to read, update and delete it as the other on every endpoint.
QuestionWhy does an OAuth client on a mobile app need PKCE?Reveal answer
The authorization code comes back through a redirect that another app on the device could intercept, and a public client has no secret to prove who redeems it. With PKCE the app sends a hash of a random verifier at the start and the verifier itself when it redeems the code, so an interceptor holding only the code cannot get tokens.
- OWASP, Password Storage Cheat Sheet (opens in a new tab) and Authentication Cheat Sheet (opens in a new tab): current algorithm and parameter guidance, credential stuffing, reset flows. OWASP, API Security Top 10 (opens in a new tab): broken object level authorization and the rest.
- IETF, RFC 6749, The OAuth 2.0 Authorization Framework (opens in a new tab), RFC 7636, PKCE (opens in a new tab) and RFC 9700, OAuth 2.0 Security Best Current Practice (opens in a new tab). OpenID Foundation, OpenID Connect Core (opens in a new tab).
- IETF, RFC 7519, JSON Web Token (opens in a new tab) and RFC 8725, JSON Web Token Best Current Practices (opens in a new tab): validation rules,
alg: none, and algorithm confusion. - W3C, Web Authentication (WebAuthn) (opens in a new tab): passkeys and origin-bound credentials.
- Ruoming Pang and others, Zanzibar: Google's Consistent, Global Authorization System (opens in a new tab), USENIX ATC 2019: relation tuples, checks, and the new enemy problem with its consistency tokens.