API Security — OWASP & Common Vulnerabilities
The OWASP API Security Top 10 (2023) explained with fixes, plus SQL injection, XSS, CSRF, SSRF, mass assignment, insecure deserialization, secrets management, security headers, supply-chain risk, and security logging.
The OWASP API Security Top 10 (2023)
| # | Risk | Example | Fix |
|---|---|---|---|
| API1 | Broken Object Level Authorization | GET /invoices/1044 returns someone else's invoice | per-object authorization on every access; tenant-scoped queries |
| API2 | Broken Authentication | no rate limit on login; weak JWT validation | MFA, rate limits, proper token validation, short-lived tokens |
| API3 | Broken Object Property Level Authorization | PATCH /me {"role":"admin"}; responses leak password_hash | explicit input/output schemas, field-level authz |
| API4 | Unrestricted Resource Consumption | ?limit=1000000, huge uploads, expensive search | rate limits, quotas, size/page caps, timeouts, cost limits |
| API5 | Broken Function Level Authorization | normal user calls DELETE /admin/users/7 | role checks per function; deny by default |
| API6 | Unrestricted Access to Sensitive Business Flows | scalper bots buy all tickets | bot detection, device fingerprinting, per-account limits, CAPTCHA |
| API7 | SSRF | "import from URL" fetches cloud metadata | allow-lists, block internal ranges, isolated egress |
| API8 | Security Misconfiguration | stack traces, Access-Control-Allow-Origin: * with credentials | hardened defaults, config scanning, security headers |
| API9 | Improper Inventory Management | forgotten /v1 without auth fixes | API inventory, gateway as the only entry, retire old versions |
| API10 | Unsafe Consumption of APIs | trusting a partner API's redirects/data | validate and sanitise third-party data, TLS, timeouts |
Injection
# ✅ parameterised
cur.execute("SELECT id, name FROM product WHERE category = %s ORDER BY price LIMIT %s", (cat, limit))
# ✅ identifiers from an allow-list
SORTABLE = {"price": "price", "newest": "created_at"}
order_col = SORTABLE.get(sort, "created_at")
cur.execute(f"SELECT id, name FROM product ORDER BY {order_col} DESC LIMIT %s", (limit,))
// ✅ parameterised (node-postgres)
await pool.query("SELECT * FROM users WHERE email = $1", [email]);
// ❌ command injection
exec(`convert ${userFileName} out.png`);
// ✅ pass arguments as an array, no shell
execFile("convert", [userFileName, "out.png"]);
XSS and security headers
HTTP
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-origin
| Header | Protects against |
|---|---|
Content-Security-Policy | XSS impact, clickjacking (frame-ancestors), data injection |
Strict-Transport-Security | SSL stripping |
X-Content-Type-Options: nosniff | MIME-sniffing attacks |
Referrer-Policy | leaking URLs (tokens) to third parties |
Cross-Origin-*-Policy | cross-origin data leaks (Spectre-class) |
CSRF
SSRF-safe URL fetching
Python
import ipaddress, socket
from urllib.parse import urlparse
BLOCKED = [ipaddress.ip_network(n) for n in (
"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8",
"169.254.0.0/16", "100.64.0.0/10", "::1/128", "fc00::/7", "fe80::/10")]
def safe_target(url: str) -> str:
u = urlparse(url)
if u.scheme not in ("http", "https"):
raise ValueError("scheme not allowed")
ip = ipaddress.ip_address(socket.gethostbyname(u.hostname))
if any(ip in net for net in BLOCKED) or ip.is_reserved or ip.is_multicast:
raise ValueError("destination not allowed")
return str(ip) # connect to THIS ip (pin it) with Host/SNI set to u.hostname; disable redirects
Mass assignment
Python
class UpdateProfile(BaseModel):
model_config = {"extra": "forbid"} # unknown fields → 422
display_name: str | None = None
bio: str | None = Field(default=None, max_length=500)
# is_admin, balance, email_verified are NOT accepted here
class PublicUser(BaseModel): # explicit response shape
id: str
display_name: str
Secrets management
Other risks to know
| Risk | Mitigation |
|---|---|
Insecure deserialization (Java serialization, Python pickle, YAML load) | never deserialize untrusted data with object-instantiating formats; use JSON + schemas; yaml.safe_load |
Path traversal (../../etc/passwd) | normalise and confine paths; use IDs, not filenames |
| File upload abuse | check type by content, size limits, store outside web root/in object storage, scan, serve from another domain |
| Open redirects | allow-list redirect targets |
| Timing attacks on secrets | constant-time comparison (hmac.compare_digest) |
| Dependency / supply-chain attacks | lockfiles, pinned versions, SCA scanning (Dependabot, Snyk), SBOMs, signed artifacts (Sigstore), minimal base images |
| Verbose errors | generic messages to clients, details in logs only |
| Log injection / sensitive data in logs | structured logging, redact PII/tokens |
| Clickjacking | frame-ancestors 'none' |
Security in the development lifecycle
- Threat modelling for new features (STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege).
- SAST/DAST/SCA in CI; secret scanning; container image scanning.
- Security-focused code review checklists (authz on every endpoint!).
- Pen tests and bug bounties for public APIs.
- Audit logs for security-relevant events (logins, permission changes, data exports) shipped to tamper-resistant storage.
- Incident response runbooks: revoke tokens, rotate secrets, notify.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.