Skip to content
IRC-CodingIRC-Coding
API KeysKey ManagementAPI SecurityKey RotationSecret ManagementLeast Privilege

API Key Management: Generation, Storage & Rotation

Master API key management: secure generation, storage, rotation, revocation, scopes, and best practices.

S

schutzgeist

6 min read
API Key Management: Generation, Storage & Rotation

API Key Management

API Keys are straightforward access credentials, but they’re only secure when generated correctly, stored safely, used responsibly, and rotated on schedule.

Overview

API Key management covers the entire lifecycle of API Keys, from generation through storage, usage, rotation, and revocation. API Keys are secret strings that clients use to identify themselves and, in some cases, to authorize their actions with an API. They’re simple to implement but carry risks if exposed, copied, or left unchanged for extended periods. Solid key management generates strong, unique Keys, stores them only as hashes, transmits them over TLS, limits their scope and validity, enables effortless rotation, and supports immediate revocation. Additionally, Keys should operate under the principle of least privilege, and their usage should be tracked through logging and monitoring.

Key Components

API Key Generation

API Keys must be generated using cryptographically secure random methods. They need to be long and unique enough to resist brute-force attacks. A minimum length of 32 bytes, combined with a mix of letters, numbers, and special characters, strengthens security considerably. Keys should never be predictable or based on user data.

API Key Storage

On the server side, API Keys must never be stored in plain text. Instead, store a hash of the Key—using SHA-256 or bcrypt—alongside a reference that maps the Key to the user. The plain-text Key is shown to the user only once, during creation. On the client side, Keys should never end up in code repositories, logs, or publicly accessible configuration files.

Transport and Transmission

API Keys must always travel over HTTPS. Avoid passing them in URLs, since URLs can appear in browser history, server logs, and Referer headers. Use the Authorization header or a dedicated header like X-API-Key instead.

Scopes and Permissions

API Keys should be issued with minimal permissions. A Key for read-only access must not permit write operations. Scopes like read:users or write:orders help restrict permissions and reduce the blast radius if a Key is compromised.

API Key Rotation

Rotation means regularly—or when compromise is suspected—issuing new Keys and invalidating old ones. Supporting multiple active Keys per client streamlines rotation: the old Key remains functional while the new one is distributed. After a transition period, the old Key is disabled.

Revocation and Deactivation

API Keys must be revocable at any time without restarting the entire service. A revoked Key is rejected on the next request. Dashboards or admin APIs should allow quick blocking if a Key is exposed.

Logging and Monitoring

Usage of API Keys should be logged. Key details include timestamps, IP addresses, which Key was used, the endpoint accessed, and the result. Monitoring detects unusual patterns: sudden traffic spikes, geographic anomalies, or access to unexpected endpoints.

Secret Management

Applications that consume API Keys should use Secret Management solutions like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault. These tools store secrets encrypted, support rotation, and prevent Keys from leaking into code or configuration.

Incident Response for Leaks

If an API Key is exposed, it must be revoked immediately. Investigate whether unauthorized actions occurred. Notify customers and internal teams, and provision a replacement Key.

Documentation and Policies

Clear guidelines for generating, using, rotating, and handling API Keys are essential. Developers and customers should understand how to store Keys safely, report breaches, and know the consequences of policy violations.

Practical Example

A SaaS provider issues API Keys to customers who want to access the Orders API.

Creating a new Key:

POST /api/v1/api-keys
Authorization: Bearer USER_TOKEN
Content-Type: application/json

{
  "name": "Integration Warehouse",
  "scopes": ["read:orders", "write:shipments"]
}

Response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  "keyId": "key-abc-123",
  "key": "sk_live_51H8x...9zA2",
  "scopes": ["read:orders", "write:shipments"],
  "createdAt": "2026-07-01T10:00:00Z",
  "expiresAt": "2027-07-01T10:00:00Z"
}

The plain-text Key is displayed only once. The server stores only a hash. The customer uses the Key:

GET /api/v1/orders
Authorization: Bearer sk_live_51H8x...9zA2

If the Key leaks, the customer can revoke it instantly from the dashboard and create a replacement. The old Key’s permissions are immediately invalid.

FAQ: API Key Management

1. What is an API Key?

An API Key is a secret string that a client uses to identify itself and, in some cases, authorize its actions with an API. API Keys are straightforward but less secure than token-based approaches.

2. How should an API Key be generated?

An API Key should be generated using cryptographically secure randomness, be sufficiently long and unique, and never rely on predictable patterns. A minimum of 32 bytes is recommended.

3. Should an API Key be stored in plain text?

No. The server should store only a hash of the Key. The plain-text Key is shown to the user once, at creation time.

4. What is API Key rotation?

Rotation is the process of replacing an API Key with a new one. It’s performed on a schedule or when compromise is suspected, ensuring continued security.

5. Why should API Keys be revocable?

Revocation is critical if a Key is exposed or stolen. Immediate revocation prevents misuse without requiring a service restart.

6. What are scopes in the context of API Keys?

Scopes restrict what an API Key is allowed to do. For example, a Key might grant read access to orders but deny write access. Scopes limit exposure if a Key is compromised.

7. Where should API Keys be stored on the client side?

API Keys should never be stored in public repositories, client-side code, or browser localStorage. Server-side applications should use Secret Management tools.

8. What is a Secret Management tool?

A Secret Management tool stores secrets like API Keys in encrypted form and manages their access, rotation, and auditing. Examples include HashiCorp Vault, AWS Secrets Manager, and Azure Key Vault.

9. How do you detect unusual API Key usage?

Logging and monitoring reveal unusual patterns. Watch for sudden traffic spikes, geographic anomalies, access outside normal hours, or requests to unexpected endpoints.

10. What should you do if an API Key leaks?

Revoke the Key immediately, generate a replacement, and notify your customers. Investigate whether unauthorized activity occurred.

11. Should API Keys have an expiration date?

Yes. Expiration enforces periodic rotation and reduces the risk of forgotten or unused Keys lingering indefinitely. Users can renew before expiry.

12. What’s the difference between an API Key and an OAuth2 Token?

An API Key is simple and typically long-lived. An OAuth2 Token is short-lived, issued by an authorization server, and supports fine-grained permissions and user-based access.

13. What is a Key prefix?

A Key prefix is a recognizable beginning of an API Key, like sk_live_ or sk_test_. It helps distinguish Keys visually and prevents accidental use in the wrong environment.

14. What is a hash in the context of API Keys?

A hash is a one-way function that converts an API Key into a non-reversible value. The server compares the hash of an incoming Key against the stored hash without needing to hold the Key itself.

15. Why shouldn’t API Keys be passed in URLs?

API Keys in URLs can leak into server logs, browser history, and Referer headers. It’s safer to transmit them in the Authorization header or a dedicated header over HTTPS.

Sources

  1. https://owasp.org/API-Security/editions/2023/en/0x11-t10/
  2. https://cheatsheetseries.owasp.org/cheatsheets/Key_Management_Cheat_Sheet.html
  3. https://www.vaultproject.io/

If you want to dive deeper into API key management, secret management, and API security, we recommend the following books:

IT CyberSecurity

Books about IT security, authentication, encryption and security best practices

The Web Application Hacker's Handbook von Dafydd Stuttard, Marcus Pinto

The Web Application Hacker's Handbook von Dafydd Stuttard, Marcus Pinto

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Back to Blog
Share:

Related Posts