How to Implement API Key Authentication
Issue and verify API keys safely: store only a hash, compare in constant time, scope and expire keys, and support rotation without downtime.
On this page
Introduction
API keys authenticate machine clients: a service calling another attaches a key that identifies the caller. They are simple and widely used, and they are also bearer credentials, so the whole security depends on how they are generated, stored, verified, and scoped. A key stored in plaintext, compared with an ordinary string equality, or granted unlimited scope turns a convenience into a liability.
This tutorial implements API key authentication: generate a high-entropy key and store only its hash with a lookup prefix, verify with a constant-time comparison, attach scopes and expiry, and support rotation. It ends with tests for revocation, expiry, scope enforcement, and the invariant that the plaintext key is never stored.
Generate and store a hashed key
Generate the key from a cryptographically secure random source with enough entropy that it cannot be guessed, and format it with a recognisable prefix and an identifier segment so it is easy to spot in logs and to look up. Show the full key to the user once, at creation, and never again; the server keeps only a hash and the non-secret pieces.
Store a cryptographic hash of the key, so a read of the table does not yield usable credentials. Record the lookup prefix, the owner, the scopes, an optional expiry, and a status for revocation, but not the key itself. If you must support key rotation, allow more than one row per owner, each with its own prefix hash and expiry, so two keys are valid during the overlap.
CREATE TABLE api_keys (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
prefix text NOT NULL UNIQUE, -- non-secret, for fast lookup
key_hash text NOT NULL, -- hash of the full key; never the key
owner_id bigint NOT NULL,
scopes text[] NOT NULL DEFAULT '{}',
expires_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
Verify with a constant-time comparison
Verification parses the presented key into its prefix and secret parts, looks up the row by prefix, and compares the hash of the presented key to the stored hash using a constant-time function. A plain equality leaks information through timing about how many leading bytes matched, which can help an attacker recover a key. Constant-time comparison removes that channel, and the prefix lookup keeps the work independent of how many keys exist.
Hash the presented key with the same algorithm used at creation and compare the digests, so the comparison is over fixed-length values. Check the expiry and revocation status as part of the same verification, and return the caller’s identity and scopes to the handler. Never log the full key; log the prefix so an operator can identify which key was used without exposing it.
import { createHash, timingSafeEqual } from 'node:crypto';
function hashKey(key) {
return createHash('sha256').update(key).digest('hex');
}
function verifyKey(presented, row) {
const a = Buffer.from(hashKey(presented));
const b = Buffer.from(row.key_hash);
if (a.length !== b.length || !timingSafeEqual(a, b)) return null;
if (row.revoked_at) return null;
if (row.expires_at && new Date(row.expires_at) < new Date()) return null;
return { ownerId: row.owner_id, scopes: row.scopes };
}
Scope and expire keys
A key should grant the least it needs. Attach scopes, such as read-only versus write, and enforce them per endpoint so a compromised read key cannot mutate data. A key with no scope limit is a key whose leak is a full compromise; scoping bounds the blast radius and makes revocation less urgent when a limited key leaks.
Give keys an expiry where the use case allows, and a revocation path always. A key that never expires and can never be revoked is a permanent credential, and one leaked in a log or a repository is permanent. Support revocation as a status flag so a key can be disabled without deleting the row and losing the audit trail, and consider an automatic expiry for keys that were meant to be short-lived.
Support rotation without downtime
Rotation means replacing a key without an outage. Allow a client to have two active keys, create the new one, update the client to use it, and then revoke the old one once the new is confirmed in use. Because both are valid during the overlap, no request fails. Track last-used time per key so you can confirm the old key is no longer used before revoking it, rather than guessing.
Automate the rotation reminder by expiry or by age. A key that has been in use for a long time is a key whose exposure window is long. A scheduled check that flags keys older than a threshold, or that expires them and forces a rotation, keeps the fleet from accumulating ancient credentials. Combine the flag with last-used telemetry so you revoke only keys actually retired.
ALTER TABLE api_keys ADD COLUMN last_used_at timestamptz;
-- keys older than 90 days, with their usage, for a rotation review
SELECT prefix, owner_id, created_at, last_used_at
FROM api_keys
WHERE revoked_at IS NULL AND created_at < now() - interval '90 days'
ORDER BY last_used_at NULLS FIRST;
Test revocation, expiry, and scope
Test that a valid key authenticates and returns the owner and scopes. Test that a revoked key is rejected. Test that an expired key is rejected. Test that a key with only read scope cannot call a write endpoint. Test that the stored row contains no plaintext equal to the key, proving the hash invariant. Test that two keys for the same owner both work during an overlap, which is what rotation relies on.
KEY=$(node scripts/create-key.mjs owner=42 scopes=read)
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $KEY" http://localhost:3000/data # 200
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $KEY" -X POST http://localhost:3000/data # 403 (read scope)
node scripts/revoke-key.mjs "$KEY"
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $KEY" http://localhost:3000/data # 401
psql -d app -c "SELECT count(*) FROM api_keys WHERE key_hash = '$KEY';" # 0: never stored plaintext
Common pitfalls
Storing the key in plaintext, comparing with ordinary string equality, no scopes so any key grants everything, keys that never expire and cannot be revoked, logging the full key, and rotating without an overlap window so the switch causes an outage are the recurring mistakes. Hashing, a constant-time compare with a prefix lookup, scopes, expiry and revocation, prefix-only logging, and dual-key overlap address them.
Conclusion
An API key is a bearer credential, so handle it like one. Generate high entropy, store only a hash with a lookup prefix, verify in constant time, attach scopes and expiry, support revocation, and rotate with two keys overlapping. Self-check by asserting a revoked key is rejected and that no plaintext key exists in the table. Then a key is a controllable, least-privilege credential instead of a permanent master secret.
Sources: OWASP: API key management, OWASP: Authentication cheat sheet, RFC 2104: HMAC.
FAQ
- Should I store the API key or a hash?
- Store a hash. A key is a bearer credential, so anyone who reads the table can use it. Hashing means a database read does not grant access, and you can still verify a presented key by hashing it and comparing. Show the plaintext only once, at creation.
- Why a prefix for lookup?
- Comparing the presented key against every stored hash in constant time would be linear in the number of keys. Store a short non-secret prefix to find the candidate row quickly, then constant-time compare only the secret portion, which keeps lookup fast and the comparison safe.
Report a problem with this articleOpens a pre-filled issue on GitHub.