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.
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
| Practice | Why It Matters |
|---|---|
| Hash before storing | If your database is breached, plaintext keys expose all users |
| Use prefixes | Prefix keys (e.g., sk-live-, sk-test-) to distinguish environments and enable scanning |
| Set expiration dates | Keys without expiration are a ticking time bomb. Default to 90-day expiry. |
| Scope permissions | Each key should have explicit scopes (which models, endpoints, and operations it can access) |
| Monitor for leaks | Scan public repositories (GitHub, GitLab) for leaked keys using secret scanning tools |
| Automated rotation | Provide 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
Generate New Key
Create a new API key while the old one is still active. Provide both keys to the user through their dashboard.
Grace Period
Allow both old and new keys to work simultaneously for a defined period (typically 7-30 days).
Deprecation Notice
Send notifications (email, webhook, dashboard alerts) warning that the old key will be deactivated.
Deactivation
Revoke the old key. Return 401 with a clear error message explaining the key has been rotated.
Ready to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX