Chapter 4

Authentication & API Keys

Bearer tokens, OAuth intro, rotation, and secret storage.

Learning objectives

  • Compare API key, Bearer token, and OAuth at a high level
  • Store secrets in environment variables — never in Git
  • Plan key rotation without downtime

Authentication proves who is calling

Public read APIs are rare for infrastructure. Most require credentials in headers:

Authorization: Bearer sk_live_abc123xyz
X-API-Key: your-dns-provider-key
MethodTypical use
API keyLong-lived secret in header — DNS, monitoring, LLM vendors
Bearer tokenOAuth access token with expiry — Google, Microsoft APIs
OAuth 2.0 flowUser clicks “Connect Google” — app gets refresh token
Server-side only

Never put secret keys in browser JavaScript — users can extract them. Workshop Co.’s FAQ widget must call your backend; the backend holds the LLM key (Book 9).

Worked example — .env on the server

# /var/www/workshopco/.env (not in git — chmod 600)
ROCKETCHAT_WEBHOOK_URL=https://chat.example/hooks/abc
GOOGLE_SHEETS_KEY_FILE=/etc/workshopco/sheets-sa.json

# PHP loads via getenv() or vlucas/phpdotenv

Rotation checklist

  1. Issue new key in provider panel
  2. Update .env on server; reload app
  3. Verify traffic succeeds 15 minutes
  4. Revoke old key

Try it yourself

A contractor needs DNS API access for one week. What beats sharing Marcus's personal key?

Answer

Provider sub-account or scoped token limited to workshopco.ca zone, TTL edit only — revoke after cutover. Log all API calls if available.

Quick quiz

Why is OAuth better than emailing a password for Google Sheets access?

Answer

Scoped permissions, revocable tokens, no shared Google password, audit trail in Google admin.