API Security & Best Practices
Authentication Patterns
# JWT — stateless
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
# API Key — simple, server-to-server
Authorization: ApiKey sk_live_abc123
X-API-Key: sk_live_abc123
# OAuth 2.0 flows
# Authorization Code + PKCE — browser SPAs, mobile apps
# Client Credentials — machine-to-machine (no user)
# Device Code — TV, CLI tools
# JWT best practices
- Short access token TTL (15 min), long refresh token TTL (7d)
- Store access token in memory (not localStorage — XSS risk)
- Store refresh token in httpOnly, Secure, SameSite cookie
- Verify signature on every request
- Include jti (JWT ID) for revocation tracking
- Never store sensitive data in JWT payload (it's only base64-encoded, not encrypted)Security Checklist
Input validation — validate all inputs server-side; never trust the client
SQL injection — use parameterized queries / prepared statements, never string concatenation
Rate limiting — limit by IP and/or user; return 429 with Retry-After
CORS — restrict allowed origins; don't use wildcard (*) for authenticated APIs
HTTPS only — redirect HTTP to HTTPS; HSTS header
Error messages — never expose stack traces or internal details in production
Sensitive data — never log passwords, tokens, PII; mask in responses (SSNs, full card numbers)
Idempotency keys — for POST mutations (payments, emails) accept an Idempotency-Key header to prevent duplicates
Idempotency Reference
# Idempotent HTTP methods — safe to retry
GET — no side effects
HEAD — no side effects
PUT — replace resource (same input = same result)
DELETE — deleting already-deleted = 404 (acceptable)
PATCH — NOT necessarily idempotent (depends on semantics)
# Non-idempotent
POST — creates new resource each time
# Making POST idempotent with Idempotency-Key
POST /payments
Idempotency-Key: client-generated-uuid-123
# Server behavior:
# - First request: process and store result keyed by Idempotency-Key
# - Duplicate requests: return stored result (don't process again)
# - Expiry: typically 24hKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free