← Back to Backend, page 1

backend-0013 · Easy fresher

How should a service issue, store and validate API keys, and when are API keys the wrong tool?

An API key is a long random secret that identifies a calling application. Generate it with a secure random source, show it once, and store only a hash (a fast SHA-256 is fine because the key has high entropy) plus a short public prefix for lookup. Validate with a constant-time comparison, attach scopes, track last use, and support rotation and revocation. API keys identify apps, not users, so they are the wrong tool for end-user login or for fine-grained delegation (use OAuth).

Full answer

Design

  • Format: a readable prefix plus random bytes, for example sk_live_ab12cd34_<32 random bytes in base64url>. The prefix tells which environment the key is for, helps secret scanners find leaks, and gives a lookup id (ab12cd34).
  • Generate with crypto.randomBytes (at least 128 bits, 256 is common). Show the full key once at creation.
  • Store: prefix (indexed), SHA-256 of the secret part, owner, scopes, created, last used, expires, revoked flag. Never store the plain key. A slow password hash is not needed for random high entropy keys, and would slow every request.
  • Validate: parse the key, look up the record by prefix, hash the presented secret, compare with crypto.timingSafeEqual, then check revoked, expiry and scope for the endpoint.

Operations

  • Support more than one active key per account so keys can be rotated without downtime. Allow instant revocation.
  • Limit scope and rate per key. Log key id (never the key). Send keys in a header (Authorization: Bearer or X-API-Key), not in URLs, because URLs end up in logs.
  • Enable secret scanning and alert on leaks.

Limits of API keys

  • They are bearer secrets: whoever holds one is the app. They carry no user identity and no consent flow. Use OAuth 2.0 for user-delegated access and mutual TLS or signed requests for higher assurance.
javascript
const crypto = require('node:crypto');

const store = new Map();                                    // prefix -> record (a table in real life)
const sha256 = (s) => crypto.createHash('sha256').update(s).digest();

function createKey({ owner, scopes }) {
  const prefix = crypto.randomBytes(4).toString('hex');
  const secret = crypto.randomBytes(32).toString('base64url');
  store.set(prefix, { owner, scopes, hash: sha256(secret), revoked: false, lastUsed: null });
  return `sk_live_${prefix}_${secret}`;                     // returned once to the user
}

function authenticate(key, neededScope, now) {
  const match = /^sk_live_([0-9a-f]{8})_([\w-]{43})$/.exec(key || '');
  if (!match) return { ok: false, reason: 'malformed' };
  const record = store.get(match[1]);
  const given = sha256(match[2]);
  if (!record || !crypto.timingSafeEqual(given, record.hash)) return { ok: false, reason: 'invalid key' };
  if (record.revoked) return { ok: false, reason: 'revoked' };
  if (!record.scopes.includes(neededScope)) return { ok: false, reason: 'missing scope ' + neededScope };
  record.lastUsed = now;
  return { ok: true, owner: record.owner };
}

const key = createKey({ owner: 'billing-service', scopes: ['students:read'] });
console.log('key shape            :', key.replace(/_[0-9a-f]{8}_.+$/, '_<prefix>_<secret>'), '| secret length:', key.slice('sk_live_'.length + 9).length);
console.log('stored fields        :', Object.keys([...store.values()][0]).join(', '), '(no plain key)');
console.log('valid read           :', JSON.stringify(authenticate(key, 'students:read', 1)));
console.log('missing scope        :', JSON.stringify(authenticate(key, 'students:write', 2)));
console.log('altered secret       :', JSON.stringify(authenticate(key.slice(0, -1) + (key.endsWith('A') ? 'B' : 'A'), 'students:read', 3)));
store.get(key.split('_')[2]).revoked = true;
console.log('after revocation     :', JSON.stringify(authenticate(key, 'students:read', 4)));

In-memory demo with Node's crypto module. A real store is a database table with an index on the prefix. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): key shape : sk_live_<prefix>_<secret> | secret length: 43 stored fields : owner, scopes, hash, revoked, lastUsed (no plain key) valid read : {"ok":true,"owner":"billing-service"} missing scope : {"ok":false,"reason":"missing scope students:write"} altered secret : {"ok":false,"reason":"invalid key"} after revocation : {"ok":false,"reason":"revoked"}

Key points

  • Use random keys with a prefix; show them once.
  • Store a hash and a lookup prefix, never the key.
  • Compare in constant time and check scopes and revocation.
  • Support rotation with several active keys.
  • Keys identify apps, not users.

Common mistakes

  • Storing keys in plain text.
  • Putting API keys in URLs or front-end code.
  • One key forever, with no rotation.
  • No scopes, so every key can do everything.
  • Comparing keys with ===.

Follow-ups

  • Why is SHA-256 acceptable for API keys but not for passwords?
  • How would you rotate a key with zero downtime?
  • How do secret scanners find leaked keys?

Tips

  • Say 'show once, store hash'.
  • Mention prefix lookup.
  • State the limits: apps, not users.