Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Securityadvanced

API Key Rotation

Share

Implement API key rotation mechanism

Works with OpenClaude

You are a security engineer implementing API key rotation. The user wants to build a production-ready mechanism to automatically rotate API keys before expiration, maintain backward compatibility during rotation, and audit all key changes.

What to check first

  • Verify your secret management system supports key versioning (e.g., AWS Secrets Manager, HashiCorp Vault, or environment variable storage with version tracking)
  • Check if your API clients support multiple concurrent API keys or if you need a grace period strategy
  • Confirm your database schema has fields for key_hash, created_at, expires_at, status (active/inactive/revoked), and rotation_id

Steps

  1. Design a rotation schedule using a cron job (e.g., rotate every 30 days, trigger 7 days before expiration)
  2. Generate new API keys with cryptographically secure random generation (minimum 32 bytes of entropy)
  3. Store the new key in your secrets manager with status: pending and a grace period end date
  4. Update your API validation logic to accept both the current active key and the pending key during the grace period (typically 24-48 hours)
  5. Mark the old key as inactive after the grace period expires and all client connections have migrated
  6. Implement a cleanup job to delete revoked keys after a retention period (30+ days for audit trail)
  7. Log all rotation events with timestamp, key fingerprint (first 8 chars of hash), rotation reason, and performer identity
  8. Add monitoring alerts for rotation failures, orphaned keys, and unauthorized access attempts with old keys

Code

import hashlib
import secrets
import json
from datetime import datetime, timedelta
from typing import Optional, Dict
import logging

logger = logging.getLogger(__name__)

class APIKeyRotationManager:
    def __init__(self, secret_store, db_connection, rotation_interval_days=30):
        self.secret_store = secret_store  # AWS Secrets Manager, Vault, etc.
        self.db = db_connection
        self.rotation_interval_days = rotation_interval_days
        self.grace_period_hours = 48

    def generate_api_key(self) -> str:
        """Generate a cryptographically secure API key"""
        return "sk_" + secrets.token_urlsafe(32)

    def hash_key(self, api_key: str) -> str:
        """Create a hash for storage (never store raw keys)"""
        return hashlib.sha256(api_key.encode()).hexdigest()

    def rotate_key(self, client_id: str, reason: str = "scheduled") -> Dict:
        """Execute full key rotation workflow"""
        try:
            # Step 1: Generate new key
            new_key = self.generate_api_key()
            new_key_hash = self.hash_key(new_key)
            
            rotation_id = secrets.token_hex(8)
            now = datetime.utcnow()
            grace_until

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategorySecurity
Difficultyadvanced
Version1.0.0
AuthorClaude Skills Hub
securityapi-keysrotation

Install command:

curl -o ~/.claude/skills/api-key-rotation.md https://claude-skills-hub.vercel.app/skills/security/api-key-rotation.md

Related Security Skills

Other Claude Code skills in the same category — free to download.

Want a Security skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.