Intermediate

Authentication

Implement robust authentication for AI APIs with API key management, OAuth2 flows, JWT tokens, automated key rotation, and zero-trust authentication patterns.

API Key Management

API keys are the most common authentication method for AI services. Proper management is critical because a leaked AI API key can lead to massive financial exposure.

Python - Secure API Key Middleware
from fastapi import Security, HTTPException
from fastapi.security import APIKeyHeader

api_key_header = APIKeyHeader(name="X-API-Key")

async def validate_api_key(
    api_key: str = Security(api_key_header)
):
    # Hash the key before database lookup (never store plaintext)
    key_hash = hashlib.sha256(api_key.encode()).hexdigest()
    key_record = await db.api_keys.find_one({
        "hash": key_hash,
        "revoked": False,
        "expires_at": {"$gt": datetime.utcnow()}
    })

    if not key_record:
        raise HTTPException(401, "Invalid or expired API key")

    # Return key metadata for downstream authorization
    return {
        "user_id": key_record["user_id"],
        "tier": key_record["tier"],
        "scopes": key_record["scopes"],
        "rate_limit": key_record["rate_limit"],
    }

API Key Best Practices

PracticeWhy It Matters
Hash before storingIf your database is breached, plaintext keys expose all users
Use prefixesPrefix keys (e.g., sk-live-, sk-test-) to distinguish environments and enable scanning
Set expiration datesKeys without expiration are a ticking time bomb. Default to 90-day expiry.
Scope permissionsEach key should have explicit scopes (which models, endpoints, and operations it can access)
Monitor for leaksScan public repositories (GitHub, GitLab) for leaked keys using secret scanning tools
Automated rotationProvide seamless key rotation that allows old and new keys to work during a transition period

OAuth2 for AI Services

For applications where end users interact with AI through your platform, OAuth2 provides delegated authorization:

Client Credentials Flow

Server-to-server integration. The application authenticates itself (not a user) to access AI APIs. Best for backend services and automated pipelines.

Authorization Code Flow

User-facing applications. The user authorizes the application to make AI API calls on their behalf. Best for SaaS products with individual user accounts.

Token Scoping

OAuth tokens should be scoped to specific AI capabilities: ai:chat, ai:embeddings, ai:images. Never issue tokens with blanket access.

Key Rotation Strategy

  1. Generate New Key

    Create a new API key while the old one is still active. Provide both keys to the user through their dashboard.

  2. Grace Period

    Allow both old and new keys to work simultaneously for a defined period (typically 7-30 days).

  3. Deprecation Notice

    Send notifications (email, webhook, dashboard alerts) warning that the old key will be deactivated.

  4. Deactivation

    Revoke the old key. Return 401 with a clear error message explaining the key has been rotated.

Critical: AI API keys are high-value targets because they provide direct access to expensive compute. A leaked OpenAI or Anthropic API key can result in thousands of dollars in charges within hours. Always treat AI API keys with the same security as production database credentials.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.