AI API Authentication Guide: API Keys, OAuth, and Best Practices
AI API authentication protects your API key — the credential that gates spend — through key design, rotation, storage hygiene, and leak response. The stakes are direct: a leaked key on a $15/1M-token model can burn thousands per hour. Production auth stacks combine scoped API keys, short-lived tokens, and strict key management. This guide covers the complete authentication surface with code.
API Key Design: Scoping, Prefixes, and TTL
Well-designed keys carry metadata that makes them operable at scale:
# Key anatomy: drai_<scope>_<random>
# scope: pro | team | read-only | revoke-scheduled
# random: 24+ chars from a CSPRNG (not uuid4, not time-seeded)
drai_pro_a3f8c1e9b2d47f6a8c0e5d1b9a3f7c2e8d4b6a1f
drai_readonly_9c2e8d4b6a1f3a7c5e9b0d2f4a6c8e1b3d5f7a9c
Three design rules:
- Prefix per scope —
drai_pro_vsdrai_ro_lets you filter logs, apply different rate limits, and revoke by class. - CSPRNG randomness —
secrets.token_hex(24)oropenssl rand -hex 24. Never derive keys from timestamps or UUIDv4 (predictable bits). - Display-once — show the full key exactly once at creation; store only a hash server-side. Support teams can't recover it, which is a feature.
Key Storage: Where Keys Live Safely
| Context | Safe | Unsafe |
|---|---|---|
| Server code | Env vars / secrets manager (Vault, AWS SM, Doppler) | Hardcoded, .env committed to git |
| CLI tools | ~/.config/drai/credentials (0600 perms) | Shell history, exported in plaintext |
| Browser app | Backend proxy (key never in client JS) | Key in localStorage or bundle |
| CI/CD | CI secrets vault (GitHub Actions secrets) | Inline in workflow YAML |
| Serverless | Platform secrets (Lambda env, CF secrets) | Packed into deployment artifact |
The browser rule deserves emphasis: if your frontend calls the LLM API directly with a key, that key is public the moment the page loads. Always proxy through your backend, which holds the key and applies your quota logic.
Rotation: Scheduled, Not Reactive
# Rotation policy (enforce with a cron):
# 1. Create new key (same scope)
# 2. Deploy code/config to use new key
# 3. Verify traffic with zero 401s for 24h
# 4. Revoke old key
# 5. Log rotation event to audit trail
def rotate(client, old_key_id, new_key_id):
client.keys.activate(new_key_id) # step 1
deploy_config(new_key_id) # step 2
wait(24h, check_zero_401s) # step 3
client.keys.revoke(old_key_id) # step 4
audit_log("key_rotated", old=old_key_id, new=new_key_id)
Every provider-facing key should rotate quarterly at minimum, and immediately on any suspected exposure. Key IDs (not the keys themselves) belong in your config, so rotation is a two-line change.
Leak Response Playbook
- Revoke immediately — the moment a key is found in a public repo, commit history, or screenshot, revoke it. Speed beats forensics.
- Audit usage — pull the key's request logs: IPs, models, token volume, timestamps. Establish the blast radius (was it spend? data exfiltration?).
- Rotate everything adjacent — if the leak came from your server, rotate all keys that shared that environment.
- Scan for patterns — add the key prefix to secret scanners (gitleaks, trufflehog, GitHub secret scanning) so the same class of leak is caught automatically.
- Post-mortem — how did it leak? Repo? Logs? Support ticket? Fix the pipeline, not just the key.
Beyond API Keys: OAuth2, JWT, and mTLS
OAuth2 / OIDC for user-level access
When your users authenticate to use AI features, issue short-lived JWTs via OAuth2 instead of sharing your platform key:
# User token: 1h expiry, contains user_id + plan tier
{
"sub": "user_8f3a", "tier": "pro", "quota": "2M_tokens",
"exp": 1767456000, "iss": "drai", "aud": "drai-api"
}
# Your gateway validates signature + exp, then:
# 1. Looks up user quota
# 2. Applies tier-based routing (pro → gpt-5, free → mini)
# 3. Meters usage to the user_id
Short TTLs (15min-1h) mean a leaked user token is a bounded liability. Refresh tokens live server-side only.
mTLS for server-to-server
For high-security integrations (financial, healthcare), mTLS authenticates both directions with certificates. Both sides pin CAs, and rotation is certificate-based. It's the strongest option and the most operational overhead — use it when compliance demands it, not for general API access.
Server-Side Request Authentication Checklist
- Rate limit per key AND per IP (a stolen key and a bot both need limits)
- Log key ID (never the key) with every request for audit
- Reject requests with no/expired keys before touching model calls (401, not a spend)
- Enforce key scopes at the gateway, not just in docs
- Alert on unusual patterns: new geography, 10x volume spike, off-hours burst
- Hash keys at rest; compare with constant-time functions
DrAI applies these patterns server-side — scoped keys, per-key rate limits, usage audit logs, and automatic alerting on anomaly patterns. The 20-item security checklist covers the broader hardening surface, and LLM security best practices covers prompt-level threats. Start with a free key at ai.dr-ai.top/signin.
Get one API key for GPT-5, Claude 4, DeepSeek, and 18+ models
Free tier available. OpenAI-compatible. Automatic failover.
Get Your Free API Key →View Pricing