Thuta Learning
API Tutorial
IntermediateWeb DevelopmentIntermediate

Authorizing with an API Key

API TutorialLesson 735 min

What you'll walk away with

  • Send an API key in a request header instead of the query string and explain the difference
  • Write server code that looks a key up by its hash and compares it with timingSafeEqual
  • Choose between 401 and 403 and add a WWW-Authenticate challenge when the key is missing or wrong
  • Describe how scopes, prefixes and rotation keep a leaked key from becoming a disaster

Explain it simply

An API key in plain language

An API key is a long secret string that a program shows to an API so the API knows which application is calling. Think of a staff badge at an office door. The badge does not say who you are as a person; it says which company you belong to and which doors you may open. The API reads the badge on every request, looks it up, and decides whether to let the caller in, turn it away, or let it in but not through that particular door.

The key travels in a request header, so each call is an ordinary HTTP request with one extra line of identification. There is no login page and no session to maintain. That is why API keys are the simplest form of API authentication, and also one of the easiest to leak.

Problem → Why → Solution

The problem: a key that everyone can see

You paste a key into a front-end script and add it to the URL because that is the quickest way to make the call work. It works, and then the key appears in places you never planned for: the server's access log, the browser history, a screenshot in a bug report, the Referer header sent to the next site, and finally a public repository. Anyone who copies it can call the API as you, and the provider bills you for it.

leaky-client.js
// Runs in the browser: every visitor can open DevTools and read this key.
const API_KEY = "demo_live_key_do_not_use";

const url = `https://api.example.com/v1/orders?api_key=${API_KEY}`;
const res = await fetch(url);
console.log(await res.json());

Why a leaked key is so hard to take back

An API key is a bearer secret: whoever holds the string is treated as the application, and the server cannot tell a copy from the real thing. Nothing in the request proves that the caller is really your code. Your only defences are to keep the key where users cannot read it, to send it somewhere that is not logged, and to limit what any single key is allowed to do.

Core concept: the key names the application and the header carries it

An API key identifies an application or a project, not a person. When a key is valid, the server knows 'this is the reporting dashboard' or 'this is the mobile app', and it can apply the limits attached to that identity: which endpoints it may use, how many requests per minute, and which environment it belongs to. If you need to know which human user is acting, you need a user-level credential such as a token, which the next lessons cover.

The key belongs in a request header. Many APIs use X-API-Key, while others read it from Authorization or from a header with the provider's own name, so check the documentation. Putting the key in the query string (?api_key=...) is tempting because it is easy to test in a browser, but a URL is copied far more widely than a header: web servers and proxies log it, browsers store it in history, and it is sent in the Referer header when a page links elsewhere. Headers are not written to access logs by default.

On the server, never store keys in plain text. Store a hash of each key, hash the key that arrives, and compare the two hashes with crypto.timingSafeEqual, which takes the same time whether the first byte or the last byte differs. An ordinary === comparison can stop at the first different character, and that tiny timing difference is something an attacker can measure. Hashing both sides also guarantees equal lengths, which timingSafeEqual requires.

Finally, answer failures precisely. A missing or unknown key gets 401 Unauthorized, because the server could not authenticate the caller, and HTTP expects a 401 response to carry a WWW-Authenticate header describing how to authenticate. A valid key that is not allowed to perform this action gets 403 Forbidden: the server knows who you are and still says no.

SituationStatusWhat the client should do
No X-API-Key header401Add the key, then retry
Key unknown or revoked401Get a valid key; retrying will not help
Valid key, missing scope403Ask for a key with the right scope
Valid key, over quota429Wait, then retry
A badge check at the door
  1. Client sends X-API-Key in a header
  2. Server hashes the key and compares it
  3. Unknown or missing key: 401 + challenge
  4. Known key without scope: 403
  5. Known key with scope: run the handler

The key says which application is calling; the scopes attached to it say what that application may do.

General pattern

text
GET /resource HTTP/1.1
Host: api.example.com
X-API-Key: <secret key>

key = lookup(hash(request header X-API-Key))
no key or unknown key  -> 401 + WWW-Authenticate
key without the scope  -> 403
otherwise              -> 200 and the handler runs

On the client it is one extra header line; on the server there are three outcomes, checked in this order.

Worked example: a key-protected orders API

The script below starts a small HTTP server on a random free port, then calls it with fetch five times: with a valid read-only key, with no key, with a wrong key, with the read-only key on a DELETE, and with an admin key on a DELETE. The server stores only SHA-256 hashes of its keys and compares them with timingSafeEqual. Run it and watch which status each situation produces.

Every key in this script is a made-up demo value. Port 0 means the operating system picks a free port, which is why no port number appears in the output.

api-key-server.mjs
import http from "node:http";
import crypto from "node:crypto";

const sha256 = (text) => crypto.createHash("sha256").update(text).digest();

// The server keeps only a hash of each key, never the key itself.
const keyStore = [
  { id: "key_reporting", hash: sha256("demo-read-key"), scopes: ["read"] },
  { id: "key_admin", hash: sha256("demo-admin-key"), scopes: ["read", "write"] },
];

function findKey(presented) {
  if (!presented) return null;
  const digest = sha256(presented); // always 32 bytes, so timingSafeEqual cannot throw
  return keyStore.find((k) => crypto.timingSafeEqual(k.hash, digest)) ?? null;
}

const server = http.createServer((req, res) => {
  const send = (status, body, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(body));
  };
  const key = findKey(req.headers["x-api-key"]);
  if (!key) {
    const challenge = { "WWW-Authenticate": 'ApiKey realm="orders"' };
    return send(401, { error: "unauthorized" }, challenge);
  }
  const needed = req.method === "GET" ? "read" : "write";
  if (!key.scopes.includes(needed)) return send(403, { error: "forbidden" });
  send(200, { ok: true, key: key.id });
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function call(label, method, headers) {
  const res = await fetch(`${base}/v1/orders`, { method, headers });
  const challenge = res.headers.get("www-authenticate");
  const body = await res.text();
  const extra = challenge ? `  ${challenge}` : "";
  console.log(`${label.padEnd(18)} ${res.status} ${body}${extra}`);
}

await call("valid read key", "GET", { "X-API-Key": "demo-read-key" });
await call("no key", "GET", {});
await call("wrong key", "GET", { "X-API-Key": "demo-read-kez" });
await call("read key, DELETE", "DELETE", { "X-API-Key": "demo-read-key" });
await call("admin key, DELETE", "DELETE", { "X-API-Key": "demo-admin-key" });
server.close();

Code breakdown

  1. Store hashes{ id: "key_reporting", hash: sha256("demo-read-key"), scopes: ["read"] },

    Each record keeps an id, a hash of the key and the scopes it grants. The real key is not in the store, so a leaked database does not hand out working keys. (The demo writes the plain text in the source only so you can see what the client sends.)

  2. Constant-time lookupreturn keyStore.find((k) => crypto.timingSafeEqual(k.hash, digest)) ?? null;

    The incoming key's digest is compared with each stored hash using timingSafeEqual. Both digests are 32 bytes, so a length mismatch cannot throw. If nothing matches, the function returns null.

  3. 401 with a challengeconst challenge = { "WWW-Authenticate": 'ApiKey realm="orders"' };

    A missing or unknown key gets a 401 plus a WWW-Authenticate header. ApiKey is a custom scheme name rather than a standard one, so clients should not rely on the name.

  4. 403 for a missing scopeif (!key.scopes.includes(needed)) return send(403, { error: "forbidden" });

    Only after the key is accepted does the code pick the scope the method needs (read for GET, write for the rest). A missing scope gives 403, not 401, because the caller is already known.

  5. Send the headerconst res = await fetch(`${base}/v1/orders`, { method, headers });

    On the client the key travels as X-API-Key in the headers object. Nothing secret is in the URL, so the request line in a server log contains no key.

You should see
valid read key     200 {"ok":true,"key":"key_reporting"}
no key             401 {"error":"unauthorized"}  ApiKey realm="orders"
wrong key          401 {"error":"unauthorized"}  ApiKey realm="orders"
read key, DELETE   403 {"error":"forbidden"}
admin key, DELETE  200 {"ok":true,"key":"key_admin"}
What the server decides for each request
  1. Read the X-API-Key header
  2. Hash it and look it up in the store
  3. Check the scope for this method
  4. Run the handler

Key missing or unknown

401 Unauthorized + WWW-Authenticate

Key valid, scope missing

403 Forbidden

Key valid, scope present

200 OK

Header or query string?

Some APIs also accept the key in the URL as a convenience, usually so you can test in a browser address bar. The convenience has a price, because the URL is the most widely copied part of a request. The script below calls a local server twice, once with the key in the query string and once in a header, and prints what a typical access log records.

access-log-leak.mjs
import http from "node:http";

const accessLog = [];
const server = http.createServer((req, res) => {
  accessLog.push(`${req.method} ${req.url}`); // roughly what an access log records
  res.end("ok");
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

const asQuery = await fetch(`${base}/v1/orders?api_key=demo-read-key`);
await asQuery.text();
const headers = { "X-API-Key": "demo-read-key" };
const asHeader = await fetch(`${base}/v1/orders`, { headers });
await asHeader.text();

console.log(accessLog.join("\n"));
server.close();

The first log line contains a working key; the second contains nothing secret. And that is only the server's own log. A corporate proxy, a CDN, a monitoring tool and the browser history each keep their own copy of the URL.

Where the key travelsWho can end up seeing it
Query string (?api_key=...)Access logs, proxies, CDNs, browser history, the Referer header, shared links, screenshots
Request header (X-API-Key)The TLS endpoint and your own application code; not logged unless you log headers

Some keys are designed to be public, such as map keys embedded in web pages. Those providers protect them with restrictions (allowed domains or apps, quota limits) instead of secrecy. If the provider's documentation says a key is meant for browsers, restrict it exactly as described; if it does not say so, treat the key as a secret.

Comparing keys without leaking timing

Checking a key with === looks harmless, but string comparison can return as soon as it finds a different character. With enough requests, an attacker can in principle measure those microscopic differences and recover a key one character at a time. crypto.timingSafeEqual avoids that, but it throws if the two buffers have different lengths, which would itself reveal the key length. The standard fix is to hash both values first, so you always compare two 32-byte digests.

timing-safe.mjs
import crypto from "node:crypto";

try {
  crypto.timingSafeEqual(Buffer.from("demo-read-key"), Buffer.from("demo-read"));
} catch (err) {
  console.log(err.code); // buffers of different lengths are rejected outright
}

const digest = (text) => crypto.createHash("sha256").update(text).digest();
console.log(crypto.timingSafeEqual(digest("demo-read-key"), digest("demo-read-key")));
console.log(crypto.timingSafeEqual(digest("demo-read-key"), digest("demo-read")));

The first line is the error code Node reports for mismatched lengths, ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH. The next two lines show a matching and a non-matching comparison of digests. In practice network jitter makes timing attacks hard against remote servers, but the fix is a single line, so there is no reason to skip it.

Key lifecycle: prefix, scope, rotation

Give keys a visible prefix

A prefix such as sk_test_ or key_live_ lets people and secret scanners recognise a key in a log or a commit, and tells you whether it is a test or a production key.

Grant the smallest scope

Create separate keys for separate jobs: a read-only key for the dashboard, a write key for the importer. A leaked read key then cannot delete anything.

Rotate with an overlap

Issue the new key, deploy it, then revoke the old one. Accept both for a short window so rotation never causes an outage.

Revoke fast and log safely

Keep a way to disable a single key immediately, and log only an id or the last four characters, never the whole key.

In real projects

API keys in real projects

Most third-party services, such as payments, maps, email, SMS and weather, open their API with an API key. When your backend calls them, it reads the key from an environment variable or a secret manager, never from source code. When you give your own API to partners, a gateway or a middleware checks the same kind of header and tracks quota and usage per partner.

  • One key per environment: keep development, staging and production apart so a leaked test key does not touch production.
  • In CI/CD, put the key in the pipeline's secret store and check that it never prints into build logs.
  • Scan repositories for secrets; some providers also watch public repos for their own key format and warn you when one appears.
  • Watch the usage graph in the provider dashboard, because an unexpected jump is often the earliest sign that a key has leaked.

Common mistakes

Common mistakes with API keys

Putting the key in the URL

?api_key=... is the easiest thing to type in curl or a browser, but it is copied into logs, history and the Referer header. If the provider accepts a header, use the header.

Shipping the key inside front-end code or a mobile app

A static key inside browser JavaScript or a mobile package can be extracted by users. Make the call from your own backend, and let the browser talk only to that backend.

Committing the key to Git

Deleting it in the next commit leaves it in history. Once committed, deleting is not enough: revoke the key and issue a new one. Add .env to .gitignore from the very first commit.

Mixing up 401 and 403

Answering 403 for a missing key makes the client think it has a permission problem and forget to send one. Answering 401 for a valid key without scope makes it think any key swap will help. Remember it as: 401 means 'I do not know who you are', 403 means 'I know, and the answer is no'.

Best practices

Best practices

  • Send keys in a header, and only over HTTPS.
  • Store only hashes on the server and compare them with timingSafeEqual.
  • Issue each key with the smallest scope that works, and rotate on a schedule.
  • Never log a whole key; log an id or a masked form instead.

Mini challenge

Mini challenge: scoped keys with masked logs

Protect a /reports endpoint with three keys: ci-bot may only read, analyst may read and write, and old-bot has been revoked. One authenticate function decides 401, 403 or 200, and every request is recorded as a log line in which only the last four characters of the key are visible.

  • Store keys as hashes and compare them with timingSafeEqual
  • Return 401 for a missing or revoked key and 403 for a missing scope
  • Log lines look like METHOD path key=****xxxx -> status, never containing the whole key
  • Send five requests, print the log and close the server
reports-keys.mjs
import http from "node:http";
import crypto from "node:crypto";

// TODO: records = [{ id, hash, scopes, revoked }], hashing each key with sha256

// TODO: mask(key) -> "****" plus the last 4 characters, or "(none)" when missing

// TODO: authenticate(presented, scope) -> { status, error?, id? }
//   no key -> 401 | unknown or revoked key -> 401 | scope missing -> 403 | else 200

// TODO: start a server on port 0 whose handler
//   - picks the scope from the method: GET -> reports:read, others -> reports:write
//   - pushes "METHOD path key=<masked> -> status" onto a log array
//   - answers with the status and a small JSON body (never echo the key)

// TODO: send five requests with fetch, print the log lines, close the server

Expected: Five log lines: ci-bot GET gives 200, ci-bot POST gives 403, analyst POST gives 200, old-bot GET gives 401, and a GET with no key gives 401.

Show hint

Write authenticate as its own function and check in this order: no key, then unknown or revoked, then scope, then success. Returning the same error for a revoked key and an unknown key is the safer choice.

Show solution
reports-keys.mjs
import http from "node:http";
import crypto from "node:crypto";

const sha256 = (text) => crypto.createHash("sha256").update(text).digest();
const record = (id, key, scopes, revoked = false) => {
  return { id, hash: sha256(key), scopes, revoked };
};
const records = [
  record("ci-bot", "sk_test_ci_1111", ["reports:read"]),
  record("analyst", "sk_test_an_2222", ["reports:read", "reports:write"]),
  record("old-bot", "sk_test_ol_3333", ["reports:read"], true),
];

const mask = (key) => (key ? `****${key.slice(-4)}` : "(none)");

function authenticate(presented, scope) {
  if (!presented) return { status: 401, error: "missing_key" };
  const digest = sha256(presented);
  const record = records.find((r) => crypto.timingSafeEqual(r.hash, digest));
  if (!record || record.revoked) return { status: 401, error: "invalid_key" };
  if (!record.scopes.includes(scope)) return { status: 403, error: "insufficient_scope" };
  return { status: 200, id: record.id };
}

const log = [];
const server = http.createServer((req, res) => {
  const key = req.headers["x-api-key"];
  const scope = req.method === "GET" ? "reports:read" : "reports:write";
  const result = authenticate(key, scope);
  log.push(`${req.method} ${req.url} key=${mask(key)} -> ${result.status}`);
  res.writeHead(result.status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(result.status === 200 ? { ok: true } : { error: result.error }));
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function send(method, key) {
  const headers = key ? { "X-API-Key": key } : {};
  const res = await fetch(`${base}/reports`, { method, headers });
  await res.text();
}

await send("GET", "sk_test_ci_1111");
await send("POST", "sk_test_ci_1111");
await send("POST", "sk_test_an_2222");
await send("GET", "sk_test_ol_3333");
await send("GET", undefined);

console.log(log.join("\n"));
server.close();

Quick quiz 1 / 3

Which request sends an API key in the safest place?

Quick quiz 2 / 3

A server receives DELETE /v1/orders/7 with a valid key that only has the read scope. Which status is right?

Quick quiz 3 / 3

Why hash both values before calling crypto.timingSafeEqual?

What to remember

  • An API key names an application, not a user, so anyone who copies a leaked key can pose as that application.
  • Send the key in a request header rather than the query string, because URLs spread into logs, history and Referer.
  • Store hashes on the server and compare with timingSafeEqual; hashing both sides also avoids length errors.
  • 401 means the key is missing or wrong, 403 means it is valid but not permitted, and a 401 should carry WWW-Authenticate.

RFC 6750 — Bearer Token Usage — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Authorizing with an API Key | Thuta Learning