Implements authentication, authorization, encryption, secrets management, and security hardening patterns. Use when designing auth flows, managing secrets, configuring CORS, implementing rate limiting, or when asked about JWT, OAuth, password hashing, API keys, RBAC, or security best practices.
Implements authentication, authorization, encryption, secrets management, and security hardening patterns. Use when designing auth flows, managing secrets, configuring CORS, implementing rate limiting, or when asked about JWT, OAuth, password hashing, API keys, RBAC, or security best practices.
Authorization Code Flow (web apps with backend):
1. Redirect to provider: /authorize?response_type=code&client_id=...&redirect_uri=...&scope=openid email
2. User authenticates, provider redirects back with ?code=AUTHORIZATION_CODE
3. Backend exchanges code for tokens (POST /token with client_secret)
4. Backend receives access_token + id_token, creates session/JWT
PKCE Flow (SPAs, mobile): Same but with code_verifier/code_challenge instead of client_secret
NEVER use Implicit Flow (deprecated, tokens exposed in URL)
functionvalidatePassword(password: string): string[] {
consterrors: string[] = [];
if (password.length < 12) errors.push("Minimum 12 characters");
if (password.length > 128) errors.push("Maximum 128 characters");
// Check against breached password lists (haveibeenpwned API or local)// Do NOT enforce arbitrary complexity rules (uppercase + number + symbol)// NIST 800-63B recommends length over complexityreturn errors;
}
Secrets Management
# WRONG: Hardcoded values in source code# API_KEY = "some-value-here"# CORRECT: Environment variables loaded from .envfrom dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("API_KEY")
db_url = os.getenv("DATABASE_URL")
# CORRECT: Secrets manager for production# AWS: Secrets Manager, Parameter Store# GCP: Secret Manager# HashiCorp Vault for self-hosted
Secret Rotation
1. Generate new secret value
2. Deploy code that accepts BOTH old and new values
3. Update all consumers to use the new value
4. Verify old value is no longer in use
5. Revoke old value
Never: Rotate in-place without a transition period
import { z } from"zod";
// WRONG: Trusting user input directly (SQL injection risk)
app.post("/api/users", (req, res) => {
db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`);
});
// CORRECT: Validate with schema, use parameterized queriesconstCreateUserSchema = z.object({
email: z.string().email().max(255),
name: z.string().min(1).max(100).trim(),
age: z.number().int().min(13).max(150).optional(),
});
app.post("/api/users", async (req, res) => {
const result = CreateUserSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.flatten() });
}
// Use parameterized query (ORM or prepared statement)await db.user.create({ data: result.data });
});
Common Anti-Patterns Summary
AVOID DO INSTEAD
-------------------------------------------------------------------
JWT in localStorage httpOnly secure cookie (refresh), memory (access)
MD5/SHA for passwords bcrypt or argon2 with proper cost factor
Hardcoded secrets in code Environment variables + secrets manager
cors({ origin: '*' }) Explicit allowed origins list
"Invalid password" message "Invalid email or password" (no enumeration)
No rate limiting on auth Strict rate limits on login/register
Rolling your own crypto Use established libraries (jose, bcrypt)
Trusting user input Validate with zod/joi, parameterized queries
Same API key forever Rotate keys regularly, support multiple active
No HTTPS redirect Force HTTPS + HSTS header
Symmetric JWT for multi-service Use RS256/ES256 (asymmetric) for distributed
No input length limits Max length on all string inputs