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

API Key Management: Secure Generation, Storage & Rotation

Master API key management: generation, storage, rotation, revocation, scopes & best practices for secure API key handling.

S

schutzgeist

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

API Key Management

API keys are simple access credentials, but they’re only secure when generated, stored, used, and rotated properly on a regular basis.

Overview

API key management covers the entire lifecycle of an API key—from generation through storage, usage, rotation, and revocation. API keys are secret strings that clients use to identify themselves and gain authorization to an API. They’re straightforward to implement but introduce risks if exposed, copied, or left unchanged for too long. Solid key management generates strong, unique keys, stores them only as hashes, transmits them over TLS, restricts their validity and permissions, enables simple rotation, and supports immediate revocation. Keys should also follow the principle of least privilege and their usage tracked through logging and monitoring.

Key Components

API Key Generation

API keys must be generated using cryptographically secure randomness. They need to be long and unique enough to resist brute-force attacks. A minimum of 32 bytes combined with letters, numbers, and special characters strengthens security considerably. Keys should never be predictable or derived from user data.

API Key Storage

Never store API keys in plaintext on the server. Instead, hash the key using SHA-256 or bcrypt and maintain a reference linking it to the user. Show the plaintext key to the user only once at creation. On the client side, keep keys out of repositories, logs, and public configuration files.

Transport and Transmission

Always transmit API keys over HTTPS. Avoid putting them in URLs, where they can leak into browser history, server logs, and referrer headers. Use the Authorization header or a custom header like X-API-Key instead.

Scopes and Permissions

Assign API keys the minimum permissions necessary for their purpose. A read-only key should never enable write operations. Scopes such as read:users or write:orders help limit privileges and reduce damage if a key is compromised.

API Key Rotation

Rotation involves regularly issuing new keys and invalidating old ones, or doing so immediately if compromise is suspected. Supporting multiple active keys per client simplifies rotation—the old key continues working while the new one is distributed. After a grace period, the old key is disabled.

Revocation and Deactivation

API keys must be revocable at any time without restarting the entire service. A disabled key is rejected on the next request. Dashboards or management APIs should make it quick to revoke keys if they’re exposed.

Logging and Monitoring

Log all API key usage. Capture timestamps, IP addresses, which key was used, the endpoint accessed, and the result. Monitoring detects unusual patterns: sudden traffic spikes, geographic anomalies, access to unexpected endpoints, or requests outside normal hours.

Secret Management

Applications consuming API keys should use Secret Management tools like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault. These platforms store secrets encrypted, automate rotation, and prevent keys from ending up in code or configuration files.

Handling Breaches

If an API key is exposed, revoke it immediately. Investigate whether any unauthorized activity occurred. Notify affected customers and internal teams, then issue a replacement key.

Documentation and Policy

Clear guidelines on generating, using, rotating, and handling API keys matter. Developers and customers need to know how to store keys securely, report leaks, and understand the consequences of violations.

Practical Example

A SaaS provider issues API keys to customers who want access to an 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 plaintext key appears only once. On the server, only a hash is stored. The customer uses the key:

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

If the key leaks, the customer revokes it instantly from the dashboard and generates a new one. The old credential becomes invalid right away.

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 gain authorization from an API. API keys are simple to implement but less secure than token-based approaches.

2. How should an API key be generated?

An API key must 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 plaintext?

No. On the server side, only a hash of the key should be stored. The plaintext key is shown to the user only once during creation.

4. What is API key rotation?

Rotation is the process of replacing an old API key with a new one. It’s performed regularly or immediately if compromise is suspected, maintaining security over time.

5. Why should API keys be revocable?

Revocation is essential when a key is exposed or stolen. Immediate revocation stops misuse without requiring a full service restart.

6. What are scopes in API keys?

Scopes restrict an API key’s permissions. For example, a key might grant read-only access to orders while denying write access. Scopes limit the blast radius if a key is compromised.

7. Where should API keys be stored on the client?

API keys must never be stored in public repositories, client-side code, or browser LocalStorage. Server-side applications should use Secret Management tools instead.

8. What is a Secret Management tool?

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

9. How do you detect unusual API key usage?

Use logging and monitoring to detect anomalies. Watch for sudden traffic spikes, geographic outliers, access from unusual times, requests to unexpected endpoints, or patterns that deviate from the key’s normal behavior.

10. What should you do if an API key is leaked?

Revoke the key immediately and generate a replacement. Investigate whether any unauthorized activity occurred. Notify customers and relevant teams, then provide instructions for using the new key.

11. Should API keys have an expiration date?

Yes. Expiration dates enforce regular rotation and reduce risk from forgotten or unused keys. Users can renew keys before they expire.

12. What’s the difference between an API key and an OAuth2 token?

API keys are simple and typically long-lived. OAuth2 tokens are short-lived, issued by an authorization server, and support fine-grained permissions and user-specific access.

13. What is a key prefix?

A key prefix is a recognizable beginning of an API key, such as sk_live_ or sk_test_. It helps visually distinguish keys 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 transforms an API key into an irreversible value. The server compares the hash of an incoming key against the stored hash, avoiding the need to store the key itself.

15. Why shouldn’t API keys appear in URLs?

API keys in URLs can leak into server logs, browser history, and referrer headers. Transmit them in the Authorization header or a custom header over HTTPS instead.

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/

To deepen your knowledge of API key management, secret management, and API security, we recommend these 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