Security Best Practices¶
Cross-cutting controls that apply to every authentication scheme and authorization pattern in this guide. Topic-specific checklists live on each page.
Transport security¶
- TLS on every endpoint. No exceptions for "internal" traffic — use mTLS or a service mesh if you want defense in depth.
- Reject or redirect port 80 — never serve auth over plaintext.
- Enable HSTS (
Strict-Transport-Security: max-age=31536000; includeSubDomains) so browsers never retry HTTP. - Modern TLS only — TLS 1.2+; disable 1.0/1.1 and weak ciphers.
Credential & token hygiene¶
Editable source: docs/diagrams/credential-lifetime.drawio
- CSPRNG for anything security-relevant —
secrets(Py),SecureRandom(Java),crypto(Node). ≥128 bits. - Hash credentials at rest — passwords: bcrypt/argon2; API keys/refresh tokens: SHA-256 (they're already high-entropy).
- Short lifetimes — access tokens ≤15 min, sessions ≤30 min idle, API keys with explicit expiry dates.
- Rotate on a schedule and provide a revocation path that works — test it, don't just document it.
- Never in source control. Secrets in env vars, mounted files, or
a secrets manager (Vault, Secrets Manager, KMS). Scan repos with
gitleaks/trufflehogin CI.
Never log secrets¶
The most common real-world leak isn't cryptographic — it's observability pipelines:
- Scrub
Authorization,Cookie,X-API-Keyheaders from access logs. - Exclude token fields from APM/distributed tracing attributes.
- Ensure error-reporting tools (Sentry etc.) strip auth headers.
- Never put credentials in URLs — they land in logs everywhere.
Rate limiting & brute-force defense¶
- Rate-limit authentication attempts per IP and per account.
- Exponential backoff or temporary lockout after repeated failures.
- Uniform failure responses — "invalid credentials," never "user not found" vs. "wrong password" (stops user enumeration).
- Constant-time comparisons for credentials/tokens.
- CAPTCHA or proof-of-work on public login endpoints under attack.
Authentication ≠ authorization¶
Every scheme in this guide proves who the caller is. Separately enforce (details in Authorization):
- Deny by default — unmapped routes, unknown roles, and policy engine errors all result in 403.
- Scope/role checks on every endpoint — a valid token for
read:photosmust not passPOST /admin(function level). - Object-level authorization — "user is authenticated" doesn't mean "user may read this record" (IDOR/BOLA — OWASP API #1).
- Property-level authorization — explicit input/output DTOs; no mass assignment, no raw entity serialization.
- Identity and tenant from the credential — never from
user_id/tenant_idin the request (multi-tenancy). - Validate
aud— reject tokens issued for a different API (scopes & claims). - Least privilege — issue the narrowest scopes the client needs.
- Test with the wrong user — two-user and cross-tenant tests in CI (testing).
Monitoring & incident response¶
- Alert on auth anomalies: failure spikes, impossible-travel logins, token reuse after rotation, new-device access.
- Log auth events (who/when/what result) — never the credentials.
- Have a "break glass" path: global token invalidation
(
min_iatbump, signing-key rotation, session-store flush). - Practice the revocation drill before you need it.
Scheme-attack quick map¶
| Attack | Basic | API Key | JWT | OAuth | Session |
|---|---|---|---|---|---|
| Sniffing without TLS | ●●● | ●●● | ●●● | ●●● | ●●● |
| Brute force | ●●● | ●● | ●● (weak secrets) | ●● | ●●● |
| XSS theft | ●● | ●● | ●●● | ●● | ● (HttpOnly) |
| CSRF | ● | – | – | – | ●●● |
| Replay after theft | ●●● | ●●● | ●●● (until exp) | ●● | ●●● |
| Misconfiguration | ● | ● | ●●● | ●●● | ●● |
| Poor revocation | ●●● | ● | ●●● | ● | – |
● = exposure level (more dots, more risk) · – = not applicable
Editable source: docs/diagrams/attack-defense-map.drawio
Defense-in-depth layering¶
flowchart LR
A[TLS + HSTS] --> B[Strong credential<br>generation & storage]
B --> C[Rate limiting<br>& uniform errors]
C --> D[Scheme-specific<br>validation]
D --> E[Scopes & object-level<br>authorization]
E --> F[Monitoring &<br>revocation]
No single layer is sufficient — a perfectly signed JWT on plaintext HTTP is still a breach. Stack them.