API Security
OAuth 2.0 for APIs, API keys, mutual TLS, scopes & audiences
Securing APIs requires layering multiple controls: OAuth 2.0 for delegated authorization with scoped access tokens, mutual TLS (mTLS) for service-to-service authentication where both parties present certificates, and API keys for simple machine-to-machine scenarios. OAuth 2.0's four flows — Authorization Code (with PKCE for public clients), Client Credentials (service-to-service), Device Code (TV/CLI), and Implicit (deprecated) — address different client trust levels. Tokens should be short-lived (15 minutes for access tokens, 7–30 days for refresh tokens) to limit the blast radius of compromise.
Key Points
- OAuth 2.0 scopes define the minimum necessary permissions: scope=read:orders is safer than scope=admin; validate scopes in the resource server, not just at the authorization server.
- JWT structure: Header.Payload.Signature (base64url encoded, dot-separated); validate: signature (RS256/ES256 preferred over HS256), exp claim, iss claim, aud claim — all four, every time.
- API keys: hash the key before storing (SHA-256); return the plaintext key only once at creation; prefix keys with a vendor identifier (sk_live_... or pk_test_...) to enable secret scanning in git commits.
- mTLS: both client and server present X.509 certificates; server validates client cert against a trusted CA; commonly used in service mesh (Istio) and financial API integrations (PSD2 Open Banking).
- Token introspection (RFC 7662): resource server calls authorization server to check if a token is active — necessary for immediate revocation; add a short local cache (30 seconds) to avoid per-request introspection overhead.
- PKCE (Proof Key for Code Exchange): public clients (SPAs, mobile) generate a code_verifier and send its hash (code_challenge) in the auth request; server verifies verifier at token exchange — prevents authorization code interception.
- Rate limiting by API key prevents credential stuffing and key abuse; implement per-key and per-IP limits; detect patterns (100 failed auth attempts in 60 seconds) and temporarily block the key.
- Sensitive data in APIs: never return full PANs, SSNs, or raw secrets — mask or tokenize; use field-level encryption for PCI-DSS scope reduction; validate output schema to prevent accidental data leakage.
Real-World Example
Twilio's API security model uses account SID + auth token for basic auth, or API keys with restricted scopes for production; all API calls require HTTPS; Twilio monitors for auth token exposure in public GitHub repos and auto-rotates them. Open Banking (PSD2) mandates mTLS + OAuth 2.0 with eIDAS certificates for all payment initiation API calls between banks and TPPs in the EU.