Stage 3 · Build
Advanced Auth & Tenant Security
API Key Management
Issue hashed API keys with prefixes, scopes, last-used timestamps, quotas, and rotation endpoints.
Why API Keys
API keys authenticate third-party integrations, CLI tools, and service-to-service communication. Unlike user sessions, API keys are long-lived and do not expire with browser sessions. They need careful management.
Key Generation
Key Storage
CREATE TABLE api_keys (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id),
name VARCHAR(255) NOT NULL,
prefix VARCHAR(20) NOT NULL,
key_hash VARCHAR(64) NOT NULL UNIQUE,
scopes TEXT[] NOT NULL DEFAULT '{}',
quota_daily INT NOT NULL DEFAULT 1000,
last_used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);Store the key hash, not the key itself. The hash is used for lookup on every request. The prefix is stored for display purposes. Include scopes and quotas for access control.
Scopes and Quotas
Key Rotation
Usage Tracking
When creating or rotating an API key, show the full key to the user once. After that, only show the prefix and last 4 characters. The full key cannot be recovered from the hash.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.