auth

API Key Management and Rotation Strategies

Sarah Chen13 min20 Feb 2024

  <h2>API Key Basics</h2>
  <p>API keys are simple authentication tokens used for service-to-service communication. While simpler than OAuth, they require careful management to stay secure.</p>
  
  <h2>Generating Secure API Keys</h2>
  <pre><code>import crypto from 'crypto';

export function generateAPIKey(): string { // Generate 32 bytes of random data const key = crypto.randomBytes(32).toString('base64url'); return sk_${key}; // Prefix for identification }

// Store hashed version in database const apiKey = generateAPIKey(); const hashedKey = await bcrypt.hash(apiKey, 10); await APIKey.create({ userId, hashedKey, name: 'Production API' });

  <h2>Key Rotation</h2>
  <p>Rotate API keys regularly (every 90 days) to limit exposure:</p>
  <pre><code>export async function rotateAPIKey(keyId: string) {

const newKey = generateAPIKey(); const hashedKey = await bcrypt.hash(newKey, 10);

// Create new key await APIKey.create({ userId: oldKey.userId, hashedKey, name: oldKey.name, expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000), });

// Mark old key for deletion in 30 days (grace period) await APIKey.findByIdAndUpdate(keyId, { deprecatedAt: new Date(), expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), });

return newKey; }

  <h2>Rate Limiting</h2>
  <p>Protect your APIs with rate limiting:</p>
  <pre><code>import rateLimit from 'express-rate-limit';

const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each key to 100 requests per windowMs message: 'Too many requests from this API key', keyGenerator: (req) => req.headers['x-api-key'], });

  <h2>Monitoring and Alerts</h2>
  <ul>
    <li>Track API key usage (requests per key)</li>
    <li>Alert on unusual patterns (spike in requests)</li>
    <li>Log all API key access</li>
    <li>Monitor for leaked keys (GitHub, public repos)</li>
  </ul>
  
  <h2>Conclusion</h2>
  <p>API keys are simple but powerful. With proper generation, storage, rotation, and monitoring, they provide secure authentication for service-to-service communication.</p>

About the Author
Sarah Chen
Sarah Chen

Cloud Infrastructure Architect

Ex-AWS Solutions Architect, 8+ years in cloud infrastructure

Cloud infrastructure specialist focusing on EU-compliant hosting solutions. Former AWS Solutions Architect, now helping European startups with deployment strategies.

Expertise:
AWSAzureKubernetesDockerEU HostingDevOps

Get notified of updates

Subscribe to receive an email when this article is updated with new information.

We'll only email you about updates to this specific article. Unsubscribe anytime.
Share this article

Tagged with

api-keyssecuritykey-rotationauthenticationapi-securitysecrets-management