Back to all terms
Authentication
Authintermediate

API Key Scoping & Rotation

The practice of limiting API key permissions to specific resources and operations, and regularly replacing keys to minimize the impact of compromise.

Also known as: Key Scoping, Key Rotation, API Key Lifecycle Management

Description

API Key Scoping restricts the permissions of each API key to only the resources and operations it needs, following the principle of least privilege. Rather than granting full API access, each key is assigned specific scopes (e.g., 'read:users', 'write:orders', 'admin:billing') that limit what the key can do. This minimizes the blast radius of a key compromise -- a leaked key with only 'read:products' scope cannot modify data or access user information.

Key rotation is the practice of periodically replacing API keys with new ones and revoking the old keys. Automated rotation prevents keys from becoming long-lived secrets that accumulate risk over time. A robust rotation mechanism supports overlapping validity periods (grace periods) where both old and new keys are accepted, allowing clients to transition without downtime. Rotation can be triggered manually, on a schedule (e.g., every 90 days), or automatically in response to suspected compromise.

Implementation requires a key management table that tracks each key's scopes, creation date, expiration, rotation history, and revocation status. The authorization middleware must check not only that the key is valid but that it has the required scopes for the requested operation. Provide clear APIs for key management: create (with scope selection), rotate (generating new key while scheduling old key expiration), revoke (immediate invalidation), and list (showing active keys and their scopes). Send notifications when keys are approaching expiration and log all key lifecycle events for audit purposes.

Prompt Snippet

Implement API key scoping with a scopes column (JSON array) in the api_keys table. Define granular scopes following the 'resource:action' pattern (e.g., 'users:read', 'orders:write'). Create middleware that parses the key, resolves its scopes, and checks against the required scope for the endpoint using a @RequiresScope('orders:write') decorator. Implement key rotation via a POST /api-keys/:id/rotate endpoint that generates a new key, sets the old key to expire after a configurable grace period (default 24 hours), and returns the new key. Track rotation lineage with a parent_key_id column. Send webhook notifications 14 days before key expiration.

Tags

api-keysscopingrotationleast-privilegelifecycle