How-to › Authenticate and authorize calls

How to issue per-customer API keys in a multi-tenant API#

Bind each API key to one tenant and one environment, resolve both before any query, and test one tenant's key against another tenant's data.

Audience
API producer
Level
intermediate
Topic
Design an authentication scheme for your API
Verified

Your API checks that a key is valid, then runs SELECT * FROM orders WHERE id = ? with the id from the path. Any customer with a working key can read, change, or delete another customer’s order by guessing or harvesting its id. A test key that resolves to the same rows as a live key lets a staging script edit production data.

What you get

You will end up with a key table that binds every key to one tenant and one environment, and a server that resolves both before any query. A test aims one tenant’s key at every endpoint. This is for you if one API serves many customers.

Short answer

Store each key as a row that names its tenant, its environment, a name, its scopes, and a SHA-256 hash of its secret, and allow many such rows per tenant. Resolve the tenant and the environment from that row before any query runs, put both in every WHERE clause, and answer another tenant’s id with the same 404 as a missing one. List keys by prefix, never by secret.

You will need

Node 22.13 or later, because the sample keeps its table in node:sqlite, which that release took out from behind a flag. Node 22 still prints an ExperimentalWarning for it on stderr. The schema is plain SQL and carries over to PostgreSQL or MySQL. Every row your API serves must already carry a tenant id; adding one is a migration of its own.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
GitHub per-user tokensKeys act as a person, with one resource owner chosen per tokenAccess follows one person’s account, so an integration’s key depends on that accountMachines call the API for a customer, not for a person
Hand-built key tableYou own the database and want the tenant check beside your queriesHashing, listing, revocation, and last-used tracking are code you write and testYou would rather buy verification, analytics, and rate limits as a service
Slack per-workspace tokensCustomers install your app, and the install is the tenant boundaryAn OAuth install flow to build and run before any customer gets a tokenCustomers want to mint keys in a dashboard without an install
Stripe live and test keysCustomers need a sandbox whose objects can never reach live dataTwo key sets per account, and a dashboard that must keep them visibly apartYou run no sandbox, so a second environment adds only bookkeeping
UnkeyYou want hosted keys tied to your tenant by externalIdEach verification calls a hosted service, and key records live with a vendorData residency or latency rules out a call outside your network

Stripe gives each account separate sandbox and live keys, and objects in one mode are not accessible to the other. Slack issues a bot token per workspace that installs the app, which suits a marketplace and burdens a plain API. Unkey links many keys to one identity through externalId and takes the verification off your hands, at the price of a network call to keys.verifyKey. GitHub’s fine-grained tokens are limited to resources owned by a single user or organization.

Give every key a tenant and an environment

The key table names the tenant and the environment in columns that cannot be null, and stores only a hash of the secret. Nothing stops a tenant from holding several keys.

CREATE TABLE api_keys (
  id           TEXT PRIMARY KEY,               -- the public part, also in the key's prefix
  tenant_id    TEXT NOT NULL REFERENCES tenants(id),
  environment  TEXT NOT NULL CHECK (environment IN ('live', 'test')),
  name         TEXT NOT NULL,                  -- what the customer called it: "billing worker"
  secret_hash  TEXT NOT NULL,                  -- SHA-256 of the secret part, hex
  scopes       TEXT NOT NULL,                  -- JSON array, such as ["orders:read"]
  created_at   TEXT NOT NULL,
  last_used_at TEXT,
  revoked_at   TEXT
);

A key reads demo_live_<id>_<secret>. The id finds the row in one indexed lookup. The environment word must match the row, so editing test to live in a key fails. A single SHA-256 is enough because the secret is 24 random bytes, not a password a person chose, so there is no dictionary to try.

Resolve the tenant from the key, before anything else

authenticate returns the tenant and the environment from the stored row. No header, query parameter, or body field can name them.

export function authenticate(db, authorization, now) {
  const m = /^Bearer (\S+)$/.exec(authorization ?? '')
  const parts = m && KEY.exec(m[1])
  if (!parts) return null
  const [, environment, id, secret] = parts
  const row = db.prepare('SELECT * FROM api_keys WHERE id = ?').get(id)
  if (!row || row.revoked_at || row.environment !== environment) return null
  const want = Buffer.from(row.secret_hash, 'hex')
  const got = Buffer.from(sha256(secret), 'hex')
  if (!timingSafeEqual(want, got)) return null
  db.prepare('UPDATE api_keys SET last_used_at = ? WHERE id = ?').run(now, id)
  return { tenantId: row.tenant_id, environment: row.environment, keyId: id, scopes: JSON.parse(row.scopes) }
}

Each query then takes that context and puts both values in its WHERE clause. An update that matches no row returns the same 404 as an id that never existed, so a probe learns nothing about other tenants.

function getOrder(db, c, id) {
  return db.prepare('SELECT id, sku, qty FROM orders WHERE id = ? AND tenant_id = ? AND environment = ?').get(id, c.tenantId, c.environment)
}
function updateOrder(db, c, id, body) {
  if (!Number.isInteger(body?.qty)) return { status: 400, body: { error: 'qty required' } }
  const r = db.prepare('UPDATE orders SET qty = ? WHERE id = ? AND tenant_id = ? AND environment = ?').run(body.qty, id, c.tenantId, c.environment)
  return r.changes ? found(getOrder(db, c, id)) : notFound()
}

OWASP ranks this failure first in its API list as broken object level authorization, and asks for a check on every endpoint that receives an object id.

Aim one tenant’s key at another tenant’s data

The demo creates tenants Acme and Globex with one live key each, plus a test key for Acme. It then calls every route in the server’s route table with Acme’s key and Globex’s ids.

node demo.mjs
Acme's live key against Globex's objects
  GET    /orders      200  listed 1, all Acme's: yes
  POST   /orders      201  created under ten_acme
  GET    /orders/:id  404
  PATCH  /orders/:id  404
  DELETE /orders/:id  404
  GET    /keys        200  listed 1, all Acme's: yes
  POST   /keys        201  created under ten_acme
  DELETE /keys/:id    404
Globex's order after the run: qty 5, 1 order(s)
Globex's key after the run: not revoked
Acme's test key reading Acme's live order: 404
Acme's key listing
[
  {
    "prefix": "demo_live_dth5racwx7f3orhx",
    "name": "billing worker",
    "scopes": [
      "orders:read",
      "orders:write",
      "keys:manage"
    ],
    "created": "2026-11-30T09:00:00.000Z",
    "lastUsed": "2026-11-30T09:00:25.000Z",
    "revoked": null
  },
  {
    "prefix": "demo_live_bxkmg54slvodop2x",
    "name": "probe",
    "scopes": [
      "orders:read"
    ],
    "created": "2026-11-30T09:00:20.000Z",
    "lastUsed": null,
    "revoked": null
  }
]
secret or hash in the listing: no

The two collection writes succeeded, but inside Acme’s own tenant. The listing gives a dashboard what it needs to tell keys apart and spot an unused one,1 and nothing that authenticates.

Check it worked

The suite walks the same route table, so an endpoint added to ROUTES joins the cross-tenant run without another test. This is the test for routes that take an id:

test("tenant A's key against tenant B's ids: every by-id call is 404 and B's rows do not change", async (t) => {
  const f = await setup(t)
  const before = snapshot(f.db)
  for (const r of ROUTES.filter((r) => r.path.includes(':id'))) {
    const target = r.path.replace(':id', r.path.startsWith('/keys') ? f.globexKeyId : f.globexOrder)
    const res = await call(f.port, r.method, target, f.keys.acme.key, bodyFor(r))
    assert.equal(res.status, 404, `${r.method} ${r.path}`)
    assert.equal(res.text, '{"error":"not found"}', 'the same answer as a missing id')
  }
  assert.equal(snapshot(f.db), before)
})

Other tests cover the collection routes, a tenant_id smuggled into the body and the query, a test key against live rows, and an edited environment word. More send a key spliced from two tenants, SQL inside a key, a revoked key, a colliding key id, and query parameters on the listing.

node --test keys.test.mjs
1..14
# tests 14
# suites 0
# pass 14
# fail 0
# cancelled 0
# skipped 0
# todo 0

When it goes wrong

Every rotation causes an outage. The schema allows one key per tenant, so replacing it breaks every client that still holds the first one. The script runs the same two workers through both designs:

node rotation.mjs
one key per tenant: 3 failed request(s)
  1. issue a second key: UNIQUE refuses it    a:200 b:200
  2. replace the secret in place              a:401 b:401
  3. redeploy worker a with the new secret    a:200 b:401
  4. redeploy worker b with the new secret    a:200 b:200
several keys per tenant: 0 failed request(s)
  1. issue a second key                       a:200 b:200
  2. redeploy worker a with the second key    a:200 b:200
  3. redeploy worker b with the second key    a:200 b:200
  4. revoke the first key                     a:200 b:200

Stripe’s dashboard builds the same overlap into rotation: the key being replaced and its replacement both work for up to seven days after you rotate a key there.

A listing endpoint starts returning secrets. A SELECT * mapped straight to JSON sends every column, the hash among them, and every column added later. Name the columns, as listKeys does.

A leak ships although the cross-tenant test passed, because the test listed endpoints by hand and missed the added one. Drive it from the router’s own table.

When not to do this

Do not tie keys to a person when the caller is a system. A key that acts as an employee carries that person’s access and changes when their account does, so name keys after the integration that holds them.

Do not build the table when a hosted service already covers verification, rate limits per identity, and usage analytics you would otherwise write. Unkey links keys to your tenant by externalId, at the cost of a network call per verification and a vendor holding your key records.

Do not answer a cross-tenant id with 403. A 403 for someone else’s order and a 404 for a missing one tell a probe which ids exist.

Do not use one environment column as a substitute for separate data when a sandbox holds customer secrets. Stripe’s sandbox objects are not accessible from live mode at all, while here a mistyped WHERE is all that separates them.

Last verified

Verified 2026-11-30 against Node 22.23.5 and its built-in SQLite 3.54.1. Every output block is what the command preceding it printed. Stripe, Slack, GitHub, and Unkey were not run; what the page says of them was read from their documentation on the same day.

Footnotes

  1. Two vendors measure disuse with different clocks. GitHub removes personal access tokens that haven’t been used in a year. Stripe may limit a key’s access when it hasn’t been used to create transfers, payouts, or update payout destinations for over 180 days. That rule counts money leaving the account, not requests in general. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.