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:

Key Storage: Where Keys Live Safely

ContextSafeUnsafe
Server codeEnv 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 appBackend proxy (key never in client JS)Key in localStorage or bundle
CI/CDCI secrets vault (GitHub Actions secrets)Inline in workflow YAML
ServerlessPlatform 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

  1. Revoke immediately — the moment a key is found in a public repo, commit history, or screenshot, revoke it. Speed beats forensics.
  2. Audit usage — pull the key's request logs: IPs, models, token volume, timestamps. Establish the blast radius (was it spend? data exfiltration?).
  3. Rotate everything adjacent — if the leak came from your server, rotate all keys that shared that environment.
  4. Scan for patterns — add the key prefix to secret scanners (gitleaks, trufflehog, GitHub secret scanning) so the same class of leak is caught automatically.
  5. 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

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

📚 Related Reading

AI API Security Checklist: 20 Items Before You LaunchA 20-item AI API security checklist for production launches: key management, rate limiting… AI API Error Handling Guide: Retry Logic, Timeouts, and FallbacksProduction AI API error handling: retry with exponential backoff, circuit breakers, model … AI API Rate Limiting: Best Practices for High-Traffic ApplicationsMaster AI API rate limiting with exponential backoff, token bucket algorithms, request que…
🌐 English