API security

Before your code runs, a request should get past four questions: who are you, aren't you calling too often, may you do this, and is what you sent right. See which status code each one answers with, trade a refresh token, then watch four rate limiters take the same burst.

Level: IntermediateWatch: 14 steps · ~1 minuteSend as Ana, Bob or CatRecall: 3 questions · 8 cardsCompare 4 rate limitersTypeScript · nginx

What you'll take away

  • Tell a 401 from a 403, and know when logging in again won't help
  • Explain where RBAC is too wide and how an ABAC rule on the owner closes it
  • Rate-limit a burst with a 429 and Retry-After, by IP before login, by user after
  • Pair a short access token with a rotating refresh token, and catch a reused one

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
No token: 401 at the first checkstep 1 of 14
401 who?
429 too often?
403 allowed?
400 valid?
API
POST /token
no token
GET /docs/7, no token → …
Step 1 / 14 · step by step
0reached the handler
0401 who are you?
0429 too often
0403 not allowed
0400 bad body

The picture: you stand on the square at the near end of a street. Four checks stand across it, each with the status it answers when it says no (401, 429, 403, 400), and the API is at the far end. The coins beside the second check are your rate-limit bucket. The side street leads to POST /token, where refresh tokens are traded. All the numbers come from a model on this page, not from a real server.

Step 4 · Every option at once, on one clock

Compare them all: Rate limiting

Every tile is set to 5 requests a second and gets the same traffic: 6 at the end of the first second, 6 more at the start of the next, a quiet spell, then another burst. The top row is when they arrive, the bottom row when they actually reach the API. Red got a 429.

0.0 s (slowed down 2×)
Fixed windowstarts over every secondok 0 · 429 0 · busiest second 0

Use it when The simplest: one counter per caller (INCR + EXPIRE in Redis). Fine for daily or hourly quotas

Skip it when At the edge of a window: a burst at the end of one second and another at the start of the next get twice the limit through in under a second

A model: one caller, slowed down twice so you can follow. The numbers count this one run. Press any tile to see it large above, with when it fits.

Which check answers what

CheckAsksNo means
authenticationWho are you? (a token, a session, a passkey)401 Unauthorized
rate limitToo many in a short time?429 Too Many Requests + Retry-After
authorizationMay you do this, to this thing?403 Forbidden
validationIs the body what the schema says?400 Bad Request (some APIs use 422)

401 or 403?

401 means the server doesn't know who you are: no token, a forged one, an expired one. Log in or refresh, and try again. 403 means it knows exactly who you are, and the answer is still no. Logging in again won't help.

RBAC or ABAC?

RBAC gives each role a list: an editor may edit. ABAC also looks at the thing and the moment: an editor may edit only their own documents, or only in their department. Start with roles, and add an attribute rule where a role is too wide. Write the rule on the server; hiding a button in the UI is not authorization.

Why the cheap checks go first

A 401 or a 429 costs almost nothing: no database, no work. Answering them early keeps a flood from reaching the expensive part. Before login, count by IP, so nobody can guess passwords at full speed; after login, count by user or API key.

Short access, long refresh

The access token travels with every request, so it lives minutes: if it leaks, it's soon useless. The refresh token goes to one place, lives longer, and is traded for a new one each time. A spent one showing up again is the alarm.

In real code

guard.ts
// The four checks in front of a handler, in order: who are you (401), too often (429), may you (403), is the body
// right (400). A real node:http server on 127.0.0.1; the requests below are real fetch calls to it.
// Run: node guard.ts   (Node 23.6+; on Node 22: node --experimental-strip-types guard.ts)
import assert from "node:assert/strict";
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";

const SECRET = process.env.JWT_SECRET ?? "dev-only-secret"; // from the environment or a secret manager, never the code
type Role = "viewer" | "editor" | "admin";
type Claims = { sub: string; role: Role; exp: number };

const b64 = (x: object) => Buffer.from(JSON.stringify(x)).toString("base64url");
const mac = (data: string) => createHmac("sha256", SECRET).update(data).digest();
const sign = (c: Claims) => { const d = `${b64({ alg: "HS256", typ: "JWT" })}.${b64(c)}`; return `${d}.${mac(d).toString("base64url")}`; };

/** Authentication: who is this? null = we don't know (no token, a bad signature, expired). */
function whoIs(req: IncomingMessage, now: number): Claims | null {
  const [kind, token] = (req.headers.authorization ?? "").split(" ");
  if (kind !== "Bearer" || !token) return null;
  const [h, p, s] = token.split(".");
  const got = Buffer.from(s ?? "", "base64url"), want = mac(`${h}.${p}`);
  if (got.length !== want.length || !timingSafeEqual(got, want)) return null;
  const c = JSON.parse(Buffer.from(p, "base64url").toString()) as Claims;
  return c.exp > now ? c : null;
}

/** RBAC: what a role may do. ABAC on top: an editor edits only their own documents. */
const ROLE_CAN: Record<Role, string[]> = { viewer: ["GET"], editor: ["GET", "PATCH"], admin: ["GET", "PATCH", "DELETE"] };
const DOCS: Record<string, { owner: string; title: string }> = { "7": { owner: "ana", title: "Plan" }, "8": { owner: "bob", title: "Notes" } };
const allowed = (c: Claims, method: string, doc: { owner: string }) =>
  ROLE_CAN[c.role].includes(method) && (method !== "PATCH" || c.role === "admin" || doc.owner === c.sub);

/** A token bucket per caller: 5 at once, one more a second. */
const buckets = new Map<string, { tokens: number; at: number }>();
function take(key: string, now: number): number {
  const b = buckets.get(key) ?? { tokens: 5, at: now };
  const tokens = Math.min(5, b.tokens + (now - b.at) * 1);
  if (tokens < 1) { buckets.set(key, { tokens, at: now }); return Math.ceil(1 - tokens); }
  buckets.set(key, { tokens: tokens - 1, at: now });
  return 0;
}

const send = (res: ServerResponse, code: number, body?: object, headers: Record<string, string> = {}) => {
  res.writeHead(code, { "content-type": "application/json", ...headers });
  res.end(body ? JSON.stringify(body) : undefined);
};

const server = createServer(async (req, res) => {
  const now = Date.now() / 1000;
  const id = (req.url ?? "").match(/^\/docs\/(\d+)$/)?.[1];
  const doc = id ? DOCS[id] : undefined;
  if (!doc) return send(res, 404, { error: "not found" });
  const who = whoIs(req, now);
  if (!who) return send(res, 401, { error: "who are you?" }, { "www-authenticate": "Bearer" });
  const wait = take(who.sub, now);
  if (wait) return send(res, 429, { error: "too many requests" }, { "retry-after": String(wait) });
  if (!allowed(who, req.method ?? "", doc)) return send(res, 403, { error: "not allowed" });
  if (req.method === "PATCH") {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const body = JSON.parse(raw || "{}") as { title?: unknown };
    if (typeof body.title !== "string" || body.title.length < 1 || body.title.length > 200) return send(res, 400, { error: "title: 1 to 200 characters" });
    doc.title = body.title;
  }
  if (req.method === "DELETE") return send(res, 204);
  send(res, 200, doc);
});

await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const exp = Date.now() / 1000 + 15 * 60;
const token = (sub: string, role: Role, e = exp) => ({ authorization: `Bearer ${sign({ sub, role, exp: e })}` });
const call = (method: string, path: string, headers: Record<string, string> = {}, body?: object) =>
  fetch(base + path, { method, headers: { ...headers, "content-type": "application/json" }, body: body ? JSON.stringify(body) : undefined });

const codes = [
  (await call("GET", "/docs/7")).status, // no token
  (await call("GET", "/docs/7", token("ana", "viewer", Date.now() / 1000 - 1))).status, // expired
  (await call("GET", "/docs/7", token("ana", "viewer"))).status,
  (await call("DELETE", "/docs/7", token("ana", "viewer"))).status, // a viewer can't delete (RBAC)
  (await call("PATCH", "/docs/7", token("bob", "editor"), { title: "Mine now" })).status, // Ana's doc (ABAC)
  (await call("PATCH", "/docs/8", token("bob", "editor"), { title: "x".repeat(5000) })).status, // the body
  (await call("PATCH", "/docs/8", token("bob", "editor"), { title: "Notes v2" })).status,
];
const burst = await Promise.all(Array.from({ length: 8 }, () => call("GET", "/docs/8", token("cat", "admin"))));
const limited = burst.filter((r) => r.status === 429);
server.close();

assert.deepEqual(codes, [401, 401, 200, 403, 403, 400, 200]);
assert.equal(limited.length, 3);
assert.equal(limited[0].headers.get("retry-after"), "1");
console.log(`no token 401 · expired 401 · viewer reads 200 · viewer deletes 403 · Bob edits Ana's 403 · 5,000-char title 400 · Bob edits his own 200 · 8 at once: 5 × 200, 3 × 429 (Retry-After: 1)`);
Run: node guard.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: no token 401 · expired 401 · viewer reads 200 · viewer deletes 403 · Bob edits Ana's 403 · 5,000-char title 400 · Bob edits his own 200 · 8 at once: 5 × 200, 3 × 429 (Retry-After: 1)

A real node:http server on 127.0.0.1 with the checks in the lesson's order: a Bearer token (HS256, checked with node:crypto), a token bucket per caller, RBAC plus one ABAC rule, and the body's length. Then real fetch calls to it, the last 8 at once.

Common questions

What's the difference between 401 and 403?

401: the server doesn't know who you are (no token, a forged one, an expired one). Log in or refresh and try again. 403: it knows it's you, and you're not allowed to do this.

Read: 401 or 403?

RBAC or ABAC: which should I use?

RBAC looks only at the role: an editor may edit. ABAC also looks at the thing and the moment: an editor may edit only their own documents. Start with roles, and add attribute rules where a role is too wide.

Read: RBAC or ABAC?

Isn't hiding the button in the UI enough?

No. Anyone can call the API straight with curl, no page involved. Permissions have to be checked on the server, on every request; hiding the button only tidies the UI.

Should rate limits count by IP or by user?

Before login, by IP, so nobody guesses passwords at full speed. After login, by user or API key. With several servers the counter has to live in one shared place, like Redis or the gateway, or each server counts on its own.

Read: why the cheap checks go first

What should a 429 response include?

A Retry-After header saying how many seconds to wait. A well-behaved client waits that long instead of firing again at once. Many APIs also send headers with the quota left.

Why can a fixed window let more than its limit through?

It starts counting over at each window. A burst at the end of one second and another at the start of the next get twice the limit through in under a second. A sliding window counts back from now, so there's no edge to game.

Token bucket or leaky bucket: what's the difference?

A token bucket saves up tokens, so a burst up to its size gets through at once, then the refill rate rules. A leaky bucket queues requests and lets them out evenly: no bursts, but those let in wait. nginx limit_req is the second kind.

Why have both an access token and a refresh token?

The access token goes with every request, so it lives minutes and a leaked one is soon useless. The refresh token goes to one place, /token, lives longer, is swapped for a new one each time, and the server can revoke it.

Read: short access, long refresh

Next lesson

Tokens on a phoneLevel: Deep

You've seen rotation from the server's side; next, the app's side: where both tokens live, and one refresh at a time.