API keys done right

Authentication and authorization Mid-level Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

How should the server store API keys?

Options
Hint 1 of 1

Can a random 256-bit key be guessed?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A A SHA-256 hash of each random key, plus a short display prefix

Correct. A database leak doesn't expose working keys.

API keys are long and random, so a fast hash is enough: there is no small dictionary to brute-force. The server hashes the presented key and looks it up, and a leaked table holds no usable keys.

Why not the others?
  • B Plain text, so support can read them. Anyone with database access can use them.
  • C bcrypt with cost 14. Unnecessary for random keys and too slow per request.
  • D Encrypted with a key stored next to them. Same as plain text if the database leaks.

30-second answer

Generate long random keys (for example 32 bytes from a CSPRNG) with a recognisable prefix (sk_live_…) so leaks are easy to scan for. Show the full key once, store only a hash (SHA-256 is fine for random keys), and look up by hash on each request. Tie each key to an owner, scopes and environment; allow several active keys so customers can rotate without downtime; log last-used time; and revoke instantly.

Practise saying it · 30 s. No recording, just a timer

Design API keys.

Say your answer out loud, then check which of these points you covered:

  • Random, prefixed
  • Hash at rest
  • Scopes, owner
  • Rotation with multiple keys
  • Header only

Deep dive

A short visible prefix (first 8 characters) helps users identify keys in the dashboard.

Secret scanning programmes (GitHub) can notify you about leaked keys with known prefixes.

API keys identify a project, not a user; use OAuth for user-delegated access.

Send keys in a header, never in URLs (they end up in logs).

Common mistakes

  • Storing keys in plain text.
  • Keys in query strings.
  • One key per account with no rotation path.

Senior take & follow-ups

Random, prefixed, hashed at rest, scoped, rotatable, header-only.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why is SHA-256 OK for API keys but not passwords?

    Show hint

    Random 256-bit keys can't be guessed; passwords can.

  2. Why prefixes?

    Show hint

    Leak scanners and humans can recognise them.

Suggest a fix if something here is wrong or out of date.