Building Software
Sections

Contents Section 8, Security

Authentication and Authorization

Proving who someone is and deciding what they are allowed to do, on every request and for every object.

Section 8 of 9, subsection 2 of 6. Depth: do. Core 19 of 25. A 10-minute read.

Mistakes to catch in review

  1. An endpoint that returns any record whose ID you put in the URL, because it checks that you are logged in but not that the record is yours.

  2. A password-reset or invite token that never expires and still works after it has been used once.

  3. Tokens accepted without verifying their signature, algorithm or expiry.

  4. Passwords stored with a fast hash or without a salt.

Every Request, Every Record

An agent added sharing to your document app. The owner of a document can share it with a teammate as a viewer, who can read it, or as an editor, who can change it. You share a document with a colleague as a viewer and open the app as her. The Edit button is gone, so the feature looks finished. The endpoint behind the page looks like this.

TypeScript
app.patch("/api/documents/:id", requireSession, async (req, res) => {
  const role = await roleOn(req.session.userId, req.params.id); // "owner" | "editor" | "viewer" | null
  if (role === null) return res.status(404).end();

  const { rows } = await db.query(
    `UPDATE documents SET title = $1, body = $2, updated_at = now()
      WHERE id = $3
  RETURNING id, title, body`,
    [req.body.title, req.body.body, req.params.id],
  );
  res.json(rows[0]);
});

A stranger gets a 404, because the handler looks up the caller's role on this document and stops when there is none. Everyone with any role then gets the write. Your colleague opens the browser's developer tools, copies the request the page makes, changes the method to PATCH and adds a body. The document is overwritten. The hidden button kept an honest user from clicking it, and the endpoint never asked whether a viewer may edit.

The requireSession middleware did its job, and so did the role lookup. The handler confirmed who is asking and that the caller has some standing on this document. It skipped the question of what that standing allows. The plainest form of this bug is an endpoint that returns any record whose ID you put in the URL after checking only that you are logged in. This handler gets one step past that and still fails.

Two questions on every request

Authentication answers "who is making this request?" A password, a passkey or a session cookie is evidence of identity. Authorization answers "may this caller perform this action on this particular thing?" That second question has a different answer for every combination of user, action and record, so it has to be asked every time.

Authorization happens at two levels. Function-level authorization decides whether this kind of user may call this kind of endpoint at all: members may edit documents, and only admins may delete a whole workspace. Object-level authorization decides whether this caller may touch this specific record in this way: the colleague may read the quarterly plan because it was shared with her, and may not edit it. A missing object-level check is what the OWASP API Security Top 10 lists first, under the name broken object-level authorization, or BOLA. A right to a record is not one right. Reading, editing, deleting and sharing each need their own answer.

Before an endpoint reads or changes an object, it has to confirm four things:

  1. The request carries a valid credential: the session exists on the server, or the token's signature, expiry and issuer check out.
  2. The caller's role allows this action on this type of object.
  3. This specific object belongs to the caller's account, or was shared with them at a level that allows this action.
  4. Every field in the response is one this caller is allowed to see. An internal moderation note on the document row should stay on the server.

The agent's code does the first, and half of the third. Here is the handler with the action check added.

TypeScript
type Role = "owner" | "editor" | "viewer";
type Action = "read" | "edit" | "share";

const ALLOWED: Record<Action, Role[]> = {
  read: ["owner", "editor", "viewer"],
  edit: ["owner", "editor"],
  share: ["owner"],
};

async function roleOn(userId: string, documentId: string): Promise<Role | null> {
  const { rows } = await db.query(
    "SELECT role FROM document_members WHERE document_id = $1 AND user_id = $2",
    [documentId, userId],
  );
  return rows[0]?.role ?? null;
}

app.patch("/api/documents/:id", requireSession, async (req, res) => {
  const role = await roleOn(req.session.userId, req.params.id);
  if (role === null) return res.status(404).end();
  if (!ALLOWED.edit.includes(role)) return res.status(403).end();

  const { rows } = await db.query(
    `UPDATE documents SET title = $1, body = $2, updated_at = now()
      WHERE id = $3
  RETURNING id, title, body`,
    [req.body.title, req.body.body, req.params.id],
  );
  res.json(rows[0]);
});

The role is resolved on the server, from the session's user ID and the document ID in the path, and nothing in the request body can claim a role. A new action has to be added to the table on purpose, and an action missing from it is allowed to nobody. The response lists columns by name, which covers the fourth check.

A PATCH request passes requireSession, then roleOn. A diamond asks whether the caller has any role; no leads to 404 for a stranger. Yes leads to a second, highlighted diamond asking whether the role may edit; no leads to 403 for a viewer, yes leads to UPDATE for owner or editor. A note says the agent's version skipped the edit check.
A stranger stops at the role lookup with a 404, a viewer stops at the edit check with a 403, and only owners and editors reach the UPDATE; the agent's handler had no edit check.

The two refusals differ on purpose. A viewer already knows the document exists, so a 403 tells her nothing new. A stranger gets a 404, the same answer as for an ID that does not exist, so the endpoint cannot be used to learn which IDs are real.

Switching to random IDs, such as UUIDs, makes guessing harder but leaves the hole open. IDs leak through shared links, support tickets, logs and other API responses. Once someone has an ID, only the permission check stands between them and the record.

Proving the fix with a viewer and an editor

You find this bug by acting as several people. Create one account for each role, share a document at each level, then try every action as every account. The test sends its requests straight to the API with each account's cookie, the way the colleague's copied request did, so it does not depend on which buttons the interface shows.

TypeScript
import { test, expect } from "bun:test";

test("only owners and editors can change a document", async () => {
  const owner = await signUpAndLogIn("owner@example.com");
  const viewer = await signUpAndLogIn("viewer@example.com");
  const editor = await signUpAndLogIn("editor@example.com");
  const stranger = await signUpAndLogIn("stranger@example.com");
  const doc = await createDocument(owner, { title: "Q3 plan", body: "original" });
  await shareDocument(owner, doc.id, viewer.email, "viewer");
  await shareDocument(owner, doc.id, editor.email, "editor");

  const patch = (who: { cookie: string }, body: string) =>
    fetch(`${BASE_URL}/api/documents/${doc.id}`, {
      method: "PATCH",
      headers: { cookie: who.cookie, "content-type": "application/json" },
      body: JSON.stringify({ title: "Q3 plan", body }),
    });

  expect((await patch(viewer, "vandalized")).status).toBe(403);
  expect((await patch(stranger, "vandalized")).status).toBe(404);
  expect((await readDocument(owner, doc.id)).body).toBe("original");

  expect((await patch(editor, "revised")).status).toBe(200);
  expect((await readDocument(owner, doc.id)).body).toBe("revised");
});

The test reads the document back after the refused attempts, because a handler can write first and return an error afterward. The editor's request is the control. Without it, an endpoint that refuses everyone would pass, and you would have proved nothing. Run the same swap against every endpoint that takes an ID in the path, the query string or the body, including the ones that update, delete and share. A missing check on DELETE is worse than one on GET.

Storing passwords

Authentication usually starts with a password, and the way you store it decides what happens after a breach. An agent asked to "hash passwords" will sometimes write this.

TypeScript
import { createHash } from "node:crypto";

const stored = createHash("sha256").update(password).digest("hex");

SHA-256 was designed to be fast, which suits checking file integrity and works against you here. If an attacker copies your users table, they can guess passwords offline, on their own hardware, with no rate limit and no lockout. A single current gaming GPU computes billions of SHA-256 hashes per second.

Work out what that means. A password of eight lowercase letters and digits has 36⁸ possibilities, about 2.8 trillion. At ten billion guesses per second, trying every one takes under five minutes. In practice attackers start with lists of real leaked passwords, so common choices fall in the first second.

Top, no salt: two separate records, alice and carol, both point to one purple box, Same hash, where one guess cracks both. Bottom, salted: One guess, sunshine1, splits into two arrows reaching two different results, alice hash from the guess plus salt A and carol hash from the guess plus salt C.
Without salts alice and carol store the same hash, so one hashed guess cracks both; with a per-user salt the guess is hashed again with each salt, and the attacker redoes the work for each user.

Two fixes are needed. The first is a salt: a random value, different for each user, stored next to the hash and mixed into it. Without salts, two users with the same password have the same hash, and one computed guess tests every account at once. With salts, the attacker has to redo the work for each user.

The second fix is a hash designed to be slow, such as Argon2id, scrypt or bcrypt. All three mix in a per-user salt and are tunable, so the cost settings let you choose how much work each guess takes. Argon2id and scrypt raise the memory cost of a guess, which limits how many a GPU can run side by side. bcrypt raises the compute cost only. Suppose they bring the attacker down to 10,000 guesses per second. The same 2.8 trillion possibilities now take about nine years instead of five minutes. Weak passwords from a leaked list still fall, but everything else becomes expensive, and you get time to notice the breach and force resets.

A box for 2.8 trillion possible passwords of eight lowercase letters and digits branches two ways. SHA-256 at ten billion guesses per second leads to under five minutes. A slow hash at 10,000 guesses per second leads to about nine years.
The same 2.8 trillion passwords take under five minutes at SHA-256 speed and about nine years at 10,000 guesses per second.

The playground takes the attacker's side against a table stored the agent's way. Browsers do not ship Argon2id, so the slow hash it times is PBKDF2, an older design that the OWASP cheat sheet still accepts at 600,000 iterations of HMAC-SHA-256.

TypeScriptRuns in your browser
const bytes = (s: string) => new TextEncoder().encode(s);
const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
const sha256 = async (s: string) => hex(await crypto.subtle.digest("SHA-256", bytes(s)));

// The stolen users table. Passwords were stored as SHA-256 with no salt.
const users = [
  { name: "alice", hash: await sha256("sunshine1") },
  { name: "bob", hash: await sha256("vR7#qe!2Lm") },
  { name: "carol", hash: await sha256("sunshine1") },
];

// The attacker's guess list. Real lists hold billions of leaked passwords.
const guesses = ["123456", "password", "qwerty", "iloveyou", "sunshine1", "letmein"];

let computed = 0;
for (const guess of guesses) {
  const h = await sha256(guess);
  computed++;
  for (const u of users) if (u.hash === h) console.log(`cracked ${u.name}: ${guess}`);
}
console.log(`${computed} hashes checked against all ${users.length} accounts at once`);

// How fast can this one browser tab guess with SHA-256?
let n = 0;
const start = performance.now();
while (performance.now() - start < 500) await sha256(`guess-${n++}`);
console.log(`SHA-256: about ${(Math.round((n * 2) / 1000) * 1000).toLocaleString("en-US")} guesses per second`);

// One guess through a slow hash.
const material = await crypto.subtle.importKey("raw", bytes("sunshine1"), "PBKDF2", false, ["deriveBits"]);
const t = performance.now();
await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: bytes("alice-random-salt"), iterations: 600_000 }, material, 256);
console.log(`PBKDF2 at 600,000 rounds: ${Math.round(performance.now() - t)} ms per guess`);

Alice and Carol fall to the same single guess, because the same password gave them the same hash. Compare the two speeds it prints: each PBKDF2 guess costs thousands of times the work of a SHA-256 guess, and an attacker pays that price on every guess for every user.

On the server, Argon2id takes a few lines.

TypeScript
// Bun's built-in Argon2id, with its default cost settings. In Node, the argon2 package does the same job.
async function hashPassword(password: string): Promise<string> {
  return Bun.password.hash(password, { algorithm: "argon2id" }); // a random salt is generated and stored in the result
}

async function checkPassword(stored: string, attempt: string): Promise<boolean> {
  return Bun.password.verify(attempt, stored); // false on a wrong password
}

The stored string starts with $argon2id$ and carries the cost settings and the salt alongside the hash, so you can raise the cost later and rehash each user's password at their next login. To catch the mistake in review, search for md5, sha1, sha256 or sha512 anywhere near the word "password," and for any hashing call that does not generate a per-user salt.

Passkeys remove the stored secret entirely. The user's device holds a private key, the server stores only the matching public key, and each login signs a fresh challenge from the server. The browser ties each passkey to the site's domain, so a look-alike phishing domain cannot get a valid signature, and a stolen copy of your database contains nothing an attacker can log in with.

Tokens that prove nothing

After login, the server gives the client something to present on later requests. A session cookie is a random ID that points to a record on the server. A signed token, usually a JSON Web Token (JWT), carries the user's identity and an expiry time inside it, with a signature that proves the server issued it.

The signature only helps if you check it. This line reads the token's contents and verifies nothing.

TypeScript
const claims = jwt.decode(token); // jsonwebtoken: parses the payload, checks nothing

Anyone can write a token that says "sub": "admin" and it will be accepted. The correct call verifies the signature, pins the algorithm, and checks issuer and audience, and the code after it requires an expiry.

TypeScript
const claims = jwt.verify(token, publicKey, {
  algorithms: ["RS256"],
  issuer: "https://auth.example.com",
  audience: "api.example.com",
}) as jwt.JwtPayload;

if (typeof claims.exp !== "number") throw new Error("token has no expiry");

Pinning the algorithm matters because the token's own header names the algorithm used to sign it, and the attacker writes that header. Older versions of several JWT libraries accepted "alg": "none", meaning no signature at all, or could be tricked into checking an HMAC signature using the server's public key as the secret. Telling the library which algorithm you expect closes both. jwt.verify in the jsonwebtoken package rejects an expired token only when the token carries an exp claim. A token with no exp never expires, which is why the line after the call rejects any payload without a numeric one. In other libraries, confirm how expiry is checked.

The playground builds toy versions of both calls on the browser's HMAC, so it signs with HS256 where the call above uses RS256. The toy verify rejects any token that is not exactly three parts, pins the algorithm, checks the signature, issuer and audience, and requires an unexpired exp. It hands both a real token and seven bad ones.

TypeScriptRuns in your browser
const bytes = (s: string) => new TextEncoder().encode(s);
const b64url = (b: Uint8Array) => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const unb64url = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const part = (o: object) => b64url(bytes(JSON.stringify(o)));
const json = (s: string) => JSON.parse(new TextDecoder().decode(unb64url(s)));

const key = await crypto.subtle.importKey("raw", bytes("a server secret of at least 32 bytes"), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
const NOW = 1_800_000_000; // a fixed clock, in seconds

async function sign(claims: object): Promise<string> {
  const data = `${part({ alg: "HS256", typ: "JWT" })}.${part(claims)}`;
  const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, bytes(data)));
  return `${data}.${b64url(sig)}`;
}

// Like jwt.decode: reads the payload, checks nothing.
function decode(token: string) {
  return json(token.split(".")[1]);
}

const ISSUER = "https://auth.example.com";
const AUDIENCE = "api.example.com";

// Like jwt.verify with the algorithm, issuer and audience pinned, followed by the required-expiry check.
async function verify(token: string) {
  const segments = token.split(".");
  if (segments.length !== 3) throw new Error("malformed token");
  const [header, payload, sig] = segments;
  const alg = json(header).alg;
  if (alg !== "HS256") throw new Error(`algorithm ${alg} not allowed`);
  if (!(await crypto.subtle.verify("HMAC", key, unb64url(sig), bytes(`${header}.${payload}`)))) throw new Error("bad signature");
  const claims = json(payload);
  if (claims.iss !== ISSUER) throw new Error("wrong issuer");
  if (claims.aud !== AUDIENCE) throw new Error("wrong audience");
  if (typeof claims.exp !== "number") throw new Error("token has no expiry");
  if (claims.exp <= NOW) throw new Error("token expired");
  return claims;
}

const ours = { iss: ISSUER, aud: AUDIENCE };
const issued = await sign({ ...ours, sub: "user-42", exp: NOW + 900 });
const [issuedHeader, , issuedSig] = issued.split(".");

const tokens: Record<string, string> = {
  "issued by the server": issued,
  "alg none, sub admin": `${part({ alg: "none", typ: "JWT" })}.${part({ ...ours, sub: "admin", exp: NOW + 900 })}.`,
  "payload edited to admin": `${issuedHeader}.${part({ ...ours, sub: "admin", exp: NOW + 900 })}.${issuedSig}`,
  "signed, no exp": await sign({ ...ours, sub: "user-42" }),
  "signed, expired": await sign({ ...ours, sub: "user-42", exp: NOW - 60 }),
  "signed, other issuer": await sign({ iss: "https://other.example", aud: AUDIENCE, sub: "admin", exp: NOW + 900 }),
  "signed for another API": await sign({ iss: ISSUER, aud: "billing.example.com", sub: "user-42", exp: NOW + 900 }),
  "issued, extra segment": `${issued}.extra`,
};

for (const [label, token] of Object.entries(tokens)) {
  const result = await verify(token).then((c) => `accepted as ${c.sub}`, (e: Error) => `rejected, ${e.message}`);
  console.log(`${label.padEnd(24)} decode: ${decode(token).sub.padEnd(8)} verify: ${result}`);
}

Signed tokens have a cost that Evert Pot's essay on JWTs spells out: with purely stateless verification the server stores nothing, so logging a user out or revoking a stolen token does nothing until the token expires. Immediate revocation needs a server-side check, such as a denylist of token IDs or a per-user session version that each token must match. If you use stateless tokens, keep their lifetime short, minutes rather than days, and pair them with a refresh token that the server can revoke.

Reset and invite tokens

A password-reset link is a credential. Whoever holds it can take over the account. So it needs the same care as a password, and two properties the agent's version often lacks: it must expire, and it must work once.

TypeScript
import { randomBytes, createHash } from "node:crypto";

const token = randomBytes(32).toString("base64url"); // goes in the email
const tokenHash = createHash("sha256").update(token).digest("hex"); // goes in the database

await db.query(
  `INSERT INTO reset_tokens (user_id, token_hash, expires_at)
   VALUES ($1, $2, now() + interval '30 minutes')`,
  [userId, tokenHash],
);

Storing only the hash means a leaked database gives the attacker no working links. A fast hash is correct here, unlike with passwords, because the token is 256 random bits and there is nothing to guess from a list. Redeeming the token consumes it in a single statement that checks and marks it, so two simultaneous requests cannot both succeed. That statement and the password update run in one transaction, so a failure between them cannot use up the token without changing the password.

SQL
BEGIN;
UPDATE reset_tokens
   SET used_at = now()
 WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id;
-- a row came back: UPDATE users SET password_hash = $2 WHERE id = <that user_id>;
-- no row came back: ROLLBACK
COMMIT;

No row returned means the token is unknown, used or expired. Redeem it when the user submits the new-password form, not when the link is opened, because email security scanners open links automatically. After the transaction commits, invalidate the user's existing sessions and any other outstanding reset tokens.

The block above is PostgreSQL. The playground runs the same consuming statement on SQLite, which spells the clock datetime('now'), and next to it the agent's version, a lookup that only asks whether the token exists. changes() reports how many rows the last update claimed.

SQLRuns on SQLite in your browser
CREATE TABLE reset_tokens (
  token_hash TEXT PRIMARY KEY,
  user_id    INTEGER NOT NULL,
  expires_at TEXT NOT NULL,
  used_at    TEXT
);
INSERT INTO reset_tokens VALUES
  ('hash-of-link-A', 7, datetime('now', '+30 minutes'), NULL),
  ('hash-of-link-B', 8, datetime('now', '-5 minutes'), NULL);
CREATE TABLE attempts (attempt TEXT, accepted INTEGER);

-- The consuming statement, three times.
UPDATE reset_tokens SET used_at = datetime('now')
 WHERE token_hash = 'hash-of-link-A' AND used_at IS NULL AND expires_at > datetime('now');
INSERT INTO attempts VALUES ('consume: link A, first use', changes());

UPDATE reset_tokens SET used_at = datetime('now')
 WHERE token_hash = 'hash-of-link-A' AND used_at IS NULL AND expires_at > datetime('now');
INSERT INTO attempts VALUES ('consume: link A, second use', changes());

UPDATE reset_tokens SET used_at = datetime('now')
 WHERE token_hash = 'hash-of-link-B' AND used_at IS NULL AND expires_at > datetime('now');
INSERT INTO attempts VALUES ('consume: link B, expired', changes());

-- The agent's version: does a token with this hash exist?
INSERT INTO attempts SELECT 'lookup: link A, already used', count(*)
  FROM reset_tokens WHERE token_hash = 'hash-of-link-A';
INSERT INTO attempts SELECT 'lookup: link B, expired', count(*)
  FROM reset_tokens WHERE token_hash = 'hash-of-link-B';

SELECT attempt, accepted FROM attempts;

Delegated access

A user who lacks the authority asks for an action. On the safe path the request goes to a highlighted check that authorizes this user for this action, and the answer is no: refused, no action taken. A dashed arrow marked skips the check runs from the user to the integration, which uses its admin token, and a second dashed arrow runs on to Action done, for whoever asks: the confused deputy's path. A note above the check reads authorize the user first.
Authorizing the user first refuses a user who lacks the authority; the confused deputy skips that check and spends its own admin token on whoever asks.

Sometimes a user wants another system to act for them: a calendar app reading their email, or a deploy tool pushing to their repository. OAuth handles this by giving the other system an access token with a limited scope, which the user can revoke, instead of the user's password. Current guidance, collected in RFC 9700, is to use the authorization-code flow with PKCE for every kind of client.

Delegation creates a specific risk that Norm Hardy described in "The Confused Deputy": a program that holds its own broad authority gets tricked into using it for someone who lacks that authority. An agent's integration that runs with an admin token and acts on any user's request is that program. The fix is the one from the document endpoint: authorize each action for the user it acts for first, then let the integration use its own credentials, scoped to what it needs. The confused deputy skips that first step and spends its own authority on whoever asks.

An endpoint may act on a record only after a check that names the caller, the record and the action. If you cannot point to the line that ties this caller to this record for this action, the endpoint serves anyone with a login.

Check your understanding

8 questions on this lesson. Pick an answer to see whether it holds and why.

  1. 1A member of project 7 sends DELETE /api/projects/7/files/9001, and file 9001 belongs to project 12, where she has no role. What happens?
    TypeScript
    app.delete("/api/projects/:projectId/files/:fileId", requireSession, async (req, res) => {
      const member = await isMember(req.session.userId, req.params.projectId);
      if (!member) return res.status(404).end();
      await db.query("DELETE FROM files WHERE id = $1", [req.params.fileId]);
      res.status(204).end();
    });
    Show the answer

    Answer B. The check proves she belongs to project 7, the project she chose to put in the path, and the DELETE then trusts a file ID from anywhere. The query never mentions the project, so nothing compares the file's project with the one checked. It needs AND project_id = $2 with the checked project, and a check that her role allows deleting.

  2. 2Every role may read a document, and this handler checks the caller's role first. The documents table also holds moderation_note and flagged_by columns for the trust and safety team. What is still wrong?
    TypeScript
    app.get("/api/documents/:id", requireSession, async (req, res) => {
      const role = await roleOn(req.session.userId, req.params.id);
      if (role === null) return res.status(404).end();
      const { rows } = await db.query("SELECT * FROM documents WHERE id = $1", [req.params.id]);
      res.json(rows[0]);
    });
    Show the answer

    Answer D. The role check answers whether this caller may read this document, which is the object-level check. The fourth check is about the response itself: SELECT * returns internal moderation fields to every reader. List the columns the caller may see. A UUID makes IDs harder to guess and leaves the response exactly as leaky.

  3. 3An agent says this fixes password storage. An attacker steals both the users table and the application's source code. What changed for the attacker?
    TypeScript
    const SALT = "s4lt-v1";
    const stored = createHash("sha256").update(SALT + password).digest("hex");
    Show the answer

    Answer A. The constant salt is in the stolen source, and it gives two users with the same password the same hash again, so one computed guess still tests every account. It does stop the attacker from reusing tables built for unsalted SHA-256, which is a small gain. SHA-256 also stays fast, billions of guesses per second on one GPU. Use Argon2id, scrypt or bcrypt with a fresh random salt per password, generated by the hashing API or by your code when the API asks for one, and stored with the hash.

  4. 4Passwords are 10 random lowercase letters, about 1.4 × 10^14 possibilities. An attacker with the stolen table tries 10 billion SHA-256 guesses per second, or 10,000 guesses per second against Argon2id at your settings. Roughly how long does trying every password take in each case?
    Show the answer

    Answer C. 1.4 × 10^14 divided by 10^10 is 14,000 seconds, a little under 4 hours. Divided by 10^4 it is 1.4 × 10^10 seconds, about 450 years. The password's strength is the same in both cases, but the slow hash multiplies the cost of every guess by a million.

  5. 5An agent wrote this middleware for an API that accepts JWTs. What does an attacker need in order to act as any user?
    TypeScript
    const claims = jwt.decode(bearerToken) as { sub: string; exp?: number };
    if (claims.exp && claims.exp < Date.now() / 1000) return res.status(401).end();
    req.userId = claims.sub;
    Show the answer

    Answer B. jwt.decode parses the payload and checks no signature, so the claims are whatever the sender wrote. The expiry check reads an exp the attacker also controls, and skips itself when exp is missing. Use jwt.verify with the algorithm, issuer and audience pinned, and reject any token without a numeric exp.

  6. 6An app uses stateless JWTs that expire 7 days after they are issued. The server checks each token's signature and expiry and keeps no record of issued tokens. A token issued yesterday was stolen the same day, and today the user clicks Log out, which deletes the token from the browser. How long can the attacker use the stolen copy?
    Show the answer

    Answer A. Deleting the browser's copy does nothing to the attacker's copy, and with purely stateless verification the server has no record to change. Even a password change revokes nothing unless the server checks something per request. Revocation needs a server-side check, such as a denylist of token IDs or a session version, and short lifetimes limit the damage.

  7. 7An agent redeems password-reset tokens this way. Which problem remains?
    SQL
    SELECT user_id FROM reset_tokens
     WHERE token_hash = $1 AND expires_at > now();
    -- if a row came back:
    UPDATE users SET password_hash = $2 WHERE id = $3;
    UPDATE reset_tokens SET used_at = now() WHERE token_hash = $1;
    Show the answer

    Answer D. Setting used_at does nothing when the check never reads it, so the link keeps working until it expires. Two simultaneous requests can also both pass the SELECT before either marks the token. Consume it with one UPDATE ... WHERE used_at IS NULL AND expires_at > now() RETURNING user_id, in the same transaction as the password change. The expiry check here does work.

  8. 8A chat integration holds an admin token for your code host. When any chat user types /delete-branch repo branch, it deletes the branch with that token. What is the fix?
    Show the answer

    Answer C. The integration is a confused deputy: it spends its own admin authority on whoever asks. Authorize each action for the user it acts for, then use the integration's own credential, scoped to what the feature needs. Logging only records the misuse, and handing passwords to the integration is what delegated access exists to avoid.

You understand it when you can

Drill

An agent built GET /api/invoices/:id, which checks for a valid session and then returns the invoice with that ID. Find how one customer reads another customer's invoices, and write the test that proves the fix works.

Topics

Authentication
Passwords and password hashing, multi-factor authentication and passkeys.
Sessions and Tokens
Cookies, bearer tokens and signed tokens, and how to handle expiry and revocation.
Authorization Models
Roles, attributes and ownership, with permission checked on the server for every action.
Object-Level Authorization
Confirming the caller may access this specific record, a check endpoints often skip once login is confirmed.
Delegated Access
OAuth-style flows that let one system act for a user with limited, revocable scope.

Further reading

Start here

Short reads

Watch

  • OAuth 2.0 and OpenID Connect (in plain English). Nate Barbettini, 2018. 62-minute talk.

    The clearest explanation of delegated access: scopes, authorization codes, access tokens, and how OpenID Connect adds identity on top of OAuth. Its implicit-flow advice is outdated; use authorization code with PKCE instead.

  • How Passkeys Work - Computerphile. Mike Pound, 2025. 19-minute explainer.

    Explains the public-key challenge-response behind passkeys and why it resists phishing and server-side credential theft in ways passwords cannot.

Books

  • API Security in Action. Neil Madden, 2020.

    Builds an API step by step and adds authentication, session cookies versus tokens, signed and encrypted tokens, OAuth, and capability-based authorization, including expiry and revocation.

  • Hacking APIs: Breaking Web Application Programming Interfaces. Corey Ball, 2022.

    Teaches the attacker's side of BOLA and broken function-level authorization, including the two-account ID-swapping test the competencies ask for.

  • OAuth 2 in Action. Justin Richer and Antonio Sanso, 2017.

    Builds client, authorization server and protected resource from scratch, so you see how delegated, scoped, revocable access actually works and where implementations go wrong.

Primary sources