🌐 API Security Threat Landscape
APIs have become the dominant attack surface in modern applications. Unlike traditional web pages, APIs provide machine-friendly, direct access to data and business logic β often with weaker security controls than UI-facing endpoints. API attacks grew 137% in 2023 according to Salt Security research.
Why APIs Are Targeted
- Direct data access β APIs return structured data (JSON/XML), making automated exfiltration trivial compared to scraping HTML.
- Automation-friendly β REST/GraphQL endpoints are designed for programmatic access β attackers can scale attacks with simple scripts.
- Often less tested β security testing frequently focuses on the UI; underlying API endpoints may never be manually tested.
- API sprawl β organizations with microservices architectures may have hundreds of internal and external APIs with inconsistent security controls.
- Mobile app APIs β mobile apps communicate via APIs that are discoverable by extracting the APK/IPA and analyzing traffic.
Real API Breaches
- Twitter/X 2022 β IDOR in API allowed unauthenticated enumeration of user accounts by phone/email. 5.4 million user records scraped and sold. Root cause: no rate limiting, no authentication check on the lookup endpoint.
- T-Mobile 2023 β API vulnerability exposed 37 million customer records. $350M settlement. Attacker made millions of API calls over 6 weeks before detection β insufficient monitoring.
- Optus 2022 (Australia) β unauthenticated API endpoint exposed 9.8 million customer records including passport and driver's license numbers.
- Peloton 2021 β unauthenticated API returned private user data including age, city, and workout stats regardless of account privacy settings.
| Rank | OWASP API Top 10 (2023) | Description | Example |
|---|---|---|---|
| API1 | Broken Object Level Authorization | Accessing other users' objects by changing ID | GET /api/orders/12346 returns another user's order |
| API2 | Broken Authentication | Weak or absent auth mechanisms | No token expiry, brute-forceable credentials |
| API3 | Broken Object Property Level Authorization | Exposing or accepting excessive object fields | Mass assignment enabling role escalation |
| API4 | Unrestricted Resource Consumption | No rate limits; DoS or cost amplification | File conversion API called 10M times |
| API5 | Broken Function Level Authorization | Accessing admin endpoints as regular user | POST /api/admin/users accessible without admin role |
| API6 | Unrestricted Access to Sensitive Business Flows | Automating flows meant for human use | Bulk account creation, inventory clearing bots |
| API7 | Server Side Request Forgery | API fetches attacker-supplied URLs | URL import feature used to reach 169.254.169.254 |
| API8 | Security Misconfiguration | Default settings, verbose errors, open CORS | CORS allows all origins with credentials |
| API9 | Improper Inventory Management | Shadow/undocumented APIs in production | Old API version still live and unpatched |
| API10 | Unsafe Consumption of APIs | Trusting third-party API responses blindly | Injecting data from external API into SQL query |
🔐 Authentication & Authorization for APIs
API Key Management
- Generation β use CSPRNG with at least 256 bits of entropy. Format with a recognizable prefix for secret scanning (e.g., sk_live_..., ghp_...) so tools like truffleHog can identify them.
- Rotation β support key rotation without downtime. Old key grace period, new key issue, old key revoke.
- Scoping β keys should have minimum required permissions. A read-only API key cannot write even if leaked.
- Transmission β API keys in Authorization header (Bearer token style), not in URL query parameters (logged in servers, proxies, browser history).
OAuth 2.0 for APIs
- Authorization Code + PKCE β for user-delegated access from SPA or mobile apps. Prevents code interception attacks.
- Client Credentials β for machine-to-machine (M2M) API calls. No user context; the client itself is the principal. Use for microservice-to-microservice calls.
- Token introspection β validate opaque tokens server-side via the authorization server's introspection endpoint (RFC 7662). Enables real-time revocation.
- mTLS (mutual TLS) β for highest-assurance M2M; both parties present certificates. Common in financial services APIs (FAPI standard).
| Auth Method | Use Case | Security | Complexity |
|---|---|---|---|
| API Key | Server-to-server, simple integrations | Medium β no expiry by default | Low |
| JWT (short-lived) | Stateless user sessions, microservices | High if implemented correctly | Medium |
| OAuth 2.0 Auth Code + PKCE | User-delegated API access | High | MediumβHigh |
| OAuth 2.0 Client Credentials | M2M, service accounts | High | Medium |
| mTLS | Financial, healthcare high-assurance M2M | Very High | High |
🚫 API Rate Limiting & Abuse Prevention
Rate Limiting Strategies
- Per-IP β simplest; ineffective against distributed attacks using residential proxy networks.
- Per-user β authenticating requests allows user-level limits. "100 API calls per minute per user." Hard to enforce on unauthenticated endpoints.
- Per-endpoint β expensive endpoints (file processing, email send, AI inference) warrant lower limits than cheap read endpoints.
- Token bucket β smooth averaging; allows short bursts up to bucket capacity. Good for bursty but legitimate traffic patterns.
- Sliding window β more accurate than fixed window; prevents spike at window boundary. Preferred for production rate limiting.
- Return 429 Too Many Requests with Retry-After header. Never return 200 and silently drop the request.
Bot & Abuse Prevention
- Credential stuffing protection β detect and block automated login attempts. Signals: high request rate from single IP, known bad IP lists, identical user agents, sequential timing.
- API key enumeration prevention β constant-time comparison for key validation (prevent timing oracle). Return 401 for both missing and invalid keys β don't distinguish between the two.
- Cloudflare API Shield β schema validation, mTLS, rate limiting, bot detection at the edge. Integrates with Cloudflare Workers.
- AWS API Gateway throttling β per-stage and per-method throttle settings; usage plans for API key-based rate limiting.
# nginx rate limiting configuration
# Define rate limit zones
limit_req_zone $binary_remote_addr zone=api_general:10m rate=100r/m;
limit_req_zone $http_authorization zone=api_per_user:10m rate=200r/m;
limit_req_zone $binary_remote_addr zone=api_auth:10m rate=10r/m;
server {
# General API endpoints: 100 req/min per IP
location /api/ {
limit_req zone=api_general burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# Auth endpoints: strict limit (10 req/min) to prevent brute force
location /api/auth/ {
limit_req zone=api_auth burst=5 nodelay;
limit_req_status 429;
add_header Retry-After 60;
proxy_pass http://backend;
}
}
📈 GraphQL & REST Security
REST Security
- IDOR prevention β verify resource ownership on every request server-side. Use UUIDs instead of sequential integers to make ID enumeration harder (defense in depth, not a fix).
- HTTP method enforcement β accept only intended methods per endpoint. Block OPTIONS unless needed for CORS preflight. Return 405 Method Not Allowed for unintended methods.
- CORS configuration β explicit origin allowlist, never reflect arbitrary Origins, never use wildcard with credentials.
- Response filtering β don't return entire database objects; return only fields needed by the client. Prevents mass assignment and data over-exposure (API3).
- Versioning β maintain old API versions only as long as necessary. Old versions often have unpatched vulnerabilities.
GraphQL Security
- Introspection β disable in production. Introspection reveals the entire schema, making targeted attacks trivial. Use a persisted query allowlist instead.
- Depth limiting β limit query nesting depth (typically 5β10 levels) to prevent exponentially expensive queries.
- Query complexity analysis β calculate a complexity score per query; reject queries above a threshold. Libraries: graphql-depth-limit, graphql-query-complexity.
- Batching attacks β GraphQL allows multiple operations in one request. Rate limit at the operation level, not just the HTTP request level.
- Field-level authorization β authorization must be checked at the resolver level. A top-level auth check is not sufficient β resolvers can be called from multiple query paths.
- Field suggestions β GraphQL suggests similar field names when a field is misspelled. Disable in production as it leaks schema information.
| Security Consideration | REST | GraphQL |
|---|---|---|
| Endpoint enumeration | Directory brute force, JavaScript bundle analysis | Introspection query (must disable in prod) |
| Object authorization | Check ownership per ID in URL/body | Check at resolver level for each field |
| DoS via expensive queries | Pagination limits, response size limits | Depth limits, complexity analysis required |
| Over-fetching prevention | Manual response filtering / DTOs | Inherent β client requests specific fields |
| Schema discovery | OpenAPI spec may be exposed | Introspection exposes full schema |
| Rate limiting granularity | Per-endpoint | Per-operation (requires custom logic) |
🧰 API Security Testing & Governance
API Discovery & Inventory
- Shadow APIs β undocumented APIs that were never intended to be public, or legacy APIs that weren't decommissioned. Often have weaker security controls.
- Inventory APIs from: gateway logs, code scanning, network traffic analysis, JavaScript bundle analysis, mobile app decompilation.
- Every API should have: an owner, a security classification, authentication requirements, and a deprecation date if applicable.
- API gateways (Kong, AWS API Gateway, Apigee) as a single enforcement point β all external API traffic passes through, enabling consistent auth, rate limiting, and logging.
OpenAPI-Driven Security Testing
- OpenAPI (formerly Swagger) spec defines every endpoint, method, parameter, and response schema β the ground truth for API security testing.
- OWASP ZAP API scan β import OpenAPI spec for targeted scanning of all documented endpoints and parameters.
- Postman security tests β write test scripts that verify auth headers are required, responses don't leak sensitive fields, status codes are correct.
- Schemathesis β property-based API testing tool. Generates test cases from OpenAPI spec automatically, including edge cases and invalid inputs.
- Spec-based testing only covers documented endpoints β shadow API discovery requires additional techniques.
API Fuzzing & Runtime Protection
- RESTler (Microsoft) β stateful REST API fuzzer. Learns the API by exploring valid sequences, then generates malformed sequences to find crashes and logic errors.
- APIFuzzer β reads OpenAPI spec, generates invalid boundary values for each field (null, empty, very long strings, special characters, SQL/XSS payloads).
- Runtime API protection β API gateways with ML-based anomaly detection can identify attacks by detecting deviations from baseline API usage patterns.
- API gateway logging β log every API request with: timestamp, caller identity, endpoint, response code, response time, and request size for security analysis.
You Can't Secure APIs You Don't Know About
Shadow APIs β undocumented endpoints left over from old feature work, internal-only APIs accidentally exposed, third-party APIs integrated without security review β are consistently the source of major API breaches. Maintain a complete, continuously updated API inventory. Scan your own network traffic and gateway logs for API endpoints that aren't in your documentation. Every API that serves production traffic must be in scope for security review, monitoring, and access control enforcement.