OWASP Top 10 API Security Risks: Engineering Mitigation Guide
Modern cloud-native applications expose their core business logic directly through REST, GraphQL, and gRPC APIs. Unlike traditional server-rendered web applications, APIs accept structured JSON payloads, return rich object graphs, and rely on stateless bearer tokens—making authorization flaws, mass assignment, resource exhaustion, and Server-Side Request Forgery (SSRF) the primary targets for automated API abuse.
The OWASP API Security Top 10 catalogs the most critical API-specific vulnerabilities. Fixing them requires enforcing object-level ownership checks, strict schema allowlisting, gateway-level rate quotas, and egress network controls directly inside your API middleware and service layer.
OWASP API Security Top 10: Threat & Defense Matrix
Reviewing all ten OWASP API risks side-by-side maps each vulnerability class to its concrete exploit vector and engineering control:
| OWASP API Risk | Primary Exploit Vector | Root Engineering Flaw | Deterministic Mitigation |
|---|---|---|---|
| API1: Broken Object Level Authorization (BOLA / IDOR) | Changing /api/v1/invoices/1042 to 1043 to read/modify another tenant's record | Endpoint verifies authentication (JWT) but skips per-object ownership validation | Scope every database query by tenant_id / owner_id derived from the verified token |
| API2: Broken Authentication | Credential stuffing, weak HS256 JWT secrets, missing token expiration/revocation | Custom auth logic, unpinned JWT alg headers, or long-lived non-revocable tokens | Enforce RS256/EdDSA JWT pinning, short TTLs (<= 15m), MFA, and jti denylists |
| API3: Broken Object Property Level Authorization (BOPLA) | Sending {"role": "admin", "balance": 9999} in PATCH /users/me (Mass Assignment) or leaking hidden DB columns | Binding raw JSON bodies directly to ORM models or returning unprojected DB entities | Separate strict input/output DTO schemas (Pydantic extra="forbid") per role |
| API4: Unrestricted Resource Consumption | Sending limit=1000000, deep GraphQL nested queries, or huge file uploads to trigger DoS / cloud bill spikes | Missing pagination ceilings, absent token-bucket rate limits, or unbounded payload sizes | Enforce sliding-window rate limits, query depth/cost caps, and body byte limits |
| API5: Broken Function Level Authorization (BFLA) | Standard user calling DELETE /api/v1/admin/users/55 directly | Relying on frontend UI hiding admin routes without backend RBAC/ABAC middleware | Default-deny RBAC/ABAC policy decorators enforced on every route handler |
| API6: Unrestricted Access to Sensitive Business Flows | Automated bots scalping limited inventory, spamming OTP SMS, or scraping pricing | Treating automated abuse identically to normal API traffic | Device attestation, behavioral velocity quotas, and step-up challenges on sensitive flows |
| API7: Server-Side Request Forgery (SSRF) | Supplying webhook_url: "http://169.254.169.254/latest/meta-data/" to pivot internally | Fetching user-supplied URLs without DNS resolution inspection or egress isolation | Strict URL scheme/domain allowlists, private-IP CIDR blocking, and IMDSv2 enforcement |
| API8: Security Misconfiguration | Wildcard CORS (Access-Control-Allow-Origin: * with credentials), verbose stack traces, unpatched TLS | Default framework debug settings left enabled in staging/production | Hardened reverse proxy headers, disabled stack traces, and automated CI config linting |
| API9: Improper Inventory Management | Attackers targeting forgotten /api/v1-beta/ shadow endpoints lacking modern auth/rate limits | Unmaintained API versions and undocumented endpoints still routed in production | Automated OpenAPI spec generation, API gateway route registration, and sunset headers |
| API10: Unsafe Consumption of APIs | Blindly trusting third-party webhook payloads or external API responses without validation | Treating upstream partner APIs as trusted internal inputs (enabling SQLi/SSRF/deserialization) | Validate, sanitize, and apply strict timeouts/circuit breakers to all external API data |
+-----------------------------------------------------------------------------------+
| DEFENSE-IN-DEPTH API SECURITY REQUEST PIPELINE |
+-----------------------------------------------------------------------------------+
| |
| [Client / Mobile / Partner API] |
| | |
| v |
| +-----------------------------------------------------------------------------+ |
| | LAYER 1: EDGE / API GATEWAY (Envoy / Kong / WAF) | |
| | - TLS 1.3 Termination & Strict CORS Allowlist | |
| | - Token-Bucket Rate Limiting (API4) & Max Payload Size Cap (<= 1 MB) | |
| | - OpenAPI Schema & Shadow Route Blocking (API8 / API9) | |
| +-----------------------------------------------------------------------------+ |
| | |
| v |
| +-----------------------------------------------------------------------------+ |
| | LAYER 2: IDENTITY & FUNCTION AUTHORIZATION MIDDLEWARE (API2 / API5) | |
| | - Verify Pinned Asymmetric JWT (RS256/EdDSA), Issuer, Audience, & Expiry | |
| | - Enforce Role/Scope RBAC Policy Before Handler Execution | |
| +-----------------------------------------------------------------------------+ |
| | |
| v |
| +-----------------------------------------------------------------------------+ |
| | LAYER 3: SERVICE & DATA ACCESS LAYER (API1 / API3 / API7) | |
| | - Strict Input/Output DTO Projection (Blocks Mass Assignment / BOPLA) | |
| | - Tenant-Scoped SQL Queries: WHERE id = :id AND owner_id = :jwt_sub (BOLA) | |
| | - Egress DNS/IP Validator for Webhooks & External Fetchers (SSRF) | |
| +-----------------------------------------------------------------------------+ |
+-----------------------------------------------------------------------------------+
Mitigating API1 (BOLA) & API3 (BOPLA) in Service Code
Broken Object Level Authorization (BOLA) is consistently the #1 most exploited API vulnerability because static analysis tools rarely detect missing ownership predicates in SQL queries. Meanwhile, Broken Object Property Level Authorization (BOPLA) combines Excessive Data Exposure and Mass Assignment.
The FastAPI + Pydantic example below demonstrates how to eliminate both vulnerabilities simultaneously:
- Strict Input/Output DTOs (
extra="forbid"): Rejects unexpected privilege-escalation fields (is_admin,tenant_id) with HTTP422and filters outgoing responses so internal database columns (internal_risk_score,password_hash) never serialize over the wire. - Scoped Repository Queries: Binds the authenticated
current_user.user_idandcurrent_user.tenant_iddirectly into theWHEREclause rather than fetching byinvoice_idalone.
from decimal import Decimal
from typing import Annotated
from uuid import UUID
from fastapi import Depends, FastAPI, HTTPException, status
from pydantic import BaseModel, ConfigDict, Field
app = FastAPI(title="Hardened Billing API")
class AuthenticatedPrincipal(BaseModel):
user_id: UUID
tenant_id: UUID
roles: set[str]
# 1. Strict Input DTO: Rejects unknown fields like 'is_approved' or 'tenant_id' (API3 Defense)
class InvoiceUpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
memo: str = Field(min_length=1, max_length=255)
billing_email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
# 2. Strict Output DTO: Exposes only safe public fields, hiding internal audit columns (API3 Defense)
class InvoicePublicResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
invoice_id: UUID
memo: str
billing_email: str
amount_usd: Decimal
status: str
def get_current_principal() -> AuthenticatedPrincipal:
# In production, extract from verified RS256/EdDSA JWT claims
return AuthenticatedPrincipal(
user_id=UUID("11111111-1111-1111-1111-111111111111"),
tenant_id=UUID("99999999-9999-9999-9999-999999999999"),
roles={"billing:write"},
)
@app.patch("/api/v1/invoices/{invoice_id}", response_model=InvoicePublicResponse)
def update_invoice(
invoice_id: UUID,
payload: InvoiceUpdateRequest,
principal: Annotated[AuthenticatedPrincipal, Depends(get_current_principal)],
) -> InvoicePublicResponse:
# API5 (BFLA): Enforce explicit function-level permission check
if "billing:write" not in principal.roles:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient scope.")
# API1 (BOLA): Query MUST filter by BOTH invoice_id AND authenticated tenant_id
# Never execute: SELECT * FROM invoices WHERE id = :invoice_id
record = fetch_invoice_scoped(invoice_id=invoice_id, tenant_id=principal.tenant_id)
if record is None:
# Return 404 (not 403) to prevent object ID enumeration across tenants
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invoice not found.")
record["memo"] = payload.memo
record["billing_email"] = payload.billing_email
return InvoicePublicResponse.model_validate(record)
def fetch_invoice_scoped(invoice_id: UUID, tenant_id: UUID) -> dict | None:
# Simulated tenant-isolated database lookup
sample_db_row = {
"invoice_id": invoice_id,
"tenant_id": UUID("99999999-9999-9999-9999-999999999999"),
"memo": "Q4 Cloud Infrastructure",
"billing_email": "finance@acme.internal",
"amount_usd": Decimal("1450.00"),
"status": "OPEN",
"internal_fraud_score": 0.04, # Stripped automatically by InvoicePublicResponse
}
if sample_db_row["tenant_id"] != tenant_id:
return None
return sample_db_row
Defending Against API7 (Server-Side Request Forgery / SSRF)
Whenever an API accepts a user-supplied URL—such as webhook callbacks, PDF/image generators, or OAuth metadata importers—attackers attempt to pivot into internal Kubernetes services (http://kubernetes.default.svc), Redis instances, or cloud metadata endpoints (http://169.254.169.254/latest/meta-data/iam/security-credentials/).
Simple string checks (if "127.0.0.1" not in url) are trivially bypassed using decimal IP encoding (http://2130706433), IPv6 mapped addresses (http://[::ffff:127.0.0.1]), or DNS rebinding. Instead, resolve the hostname to concrete IP addresses and validate every resolved IP against non-routable CIDR blocks before opening a socket:
import ipaddress
import socket
from urllib.parse import urlparse
ALLOWED_SCHEMES = {"https"}
def validate_outbound_webhook_url(raw_url: str) -> str:
parsed = urlparse(raw_url)
if parsed.scheme not in ALLOWED_SCHEMES or not parsed.hostname:
raise ValueError("Webhook URL must use HTTPS and specify a valid hostname.")
if parsed.username or parsed.password:
raise ValueError("Embedded credentials in webhook URLs are forbidden.")
# Resolve all A and AAAA records for the target hostname
try:
addr_info = socket.getaddrinfo(parsed.hostname, parsed.port or 443, proto=socket.IPPROTO_TCP)
except socket.gaierror as exc:
raise ValueError(f"Unable to resolve webhook hostname: {parsed.hostname}") from exc
if not addr_info:
raise ValueError("Hostname resolved to zero IP addresses.")
for family, _, _, _, sockaddr in addr_info:
ip_str = sockaddr[0]
ip_obj = ipaddress.ip_address(ip_str)
# Block loopback, RFC 1918 private, link-local (169.254.0.0/16), multicast, and reserved ranges
if (
ip_obj.is_private
or ip_obj.is_loopback
or ip_obj.is_link_local
or ip_obj.is_multicast
or ip_obj.is_reserved
or ip_obj.is_unspecified
):
raise ValueError(f"Blocked SSRF attempt targeting non-public IP address: {ip_str}")
return raw_url
PUT token headers), disabled HTTP redirects (allow_redirects=False), and Kubernetes NetworkPolicy egress rules blocking pods from reaching RFC 1918 and link-local subnets.Enforcing API4 (Unrestricted Resource Consumption) & API9 (Inventory Governance)
To prevent denial-of-wallet attacks, scraping, and forgotten shadow endpoints:
- Enforce Hard Pagination Ceilings: Never pass raw client query parameters directly into
LIMITclauses. Clamplimit = min(max(request_limit, 1), 100)across every list endpoint. - Apply Multi-Tier Token-Bucket Rate Limiting: Configure your API gateway (Kong, Envoy, AWS API Gateway) with burst and sustained quotas keyed by both authenticated
sub/ API key and source IP (100 req/minstandard,5 req/minon expensive login/OTP/export endpoints), returning standardizedHTTP 429 Too Many RequestswithRetry-Afterheaders. - Eliminate Shadow & Zombie APIs (API9): Generate your OpenAPI 3.1 specification directly from code in CI/CD, sync the spec to your API gateway so any undocumented route is automatically rejected with HTTP
404, and enforce deprecation schedules (SunsetHTTP header) for legacy API versions.
Common Mistakes
- Relying on non-guessable UUIDs (
UUIDv4) as a substitute for BOLA authorization: WhileUUIDv4prevents sequential ID enumeration (1001, 1002), UUIDs routinely leak in browser histories, referrer logs, support tickets, and shared links. Every object access must still verify explicit ownership or RBAC permissions. - Allowing arbitrary HTTP redirects in outbound webhook fetchers: Even if
https://attacker.example/hookresolves to a public IP during initial validation, an HTTP302 Foundredirect tohttp://169.254.169.254/bypasses pre-request DNS checks if the HTTP client follows redirects automatically. - **Configuring
Access-Control-Allow-Origin: *alongsideAccess-Control-Allow-Credentials: trueor reflecting arbitraryOriginheaders:** Reflecting any incomingOriginheader allows malicious websites to read authenticated cross-origin API responses directly from a victim's browser.
Summary
Securing production APIs against the OWASP API Security Top 10 requires enforcing tenant-scoped database queries (BOLA), strict input/output DTO schemas (BOPLA), default-deny RBAC middleware (BFLA), pre-connection DNS/IP egress validation (SSRF), and gateway-enforced rate limits and OpenAPI route inventories. Embedding these controls directly into shared framework base classes and CI/CD pipelines ensures every new endpoint inherits strong security defaults automatically.