Application Security: Secure Coding OWASP Top 10 SAST & DAST Penetration Testing API Security Container Security
← Penetration Testing Container Security →
⏱ 12 min read πŸ“Š Advanced πŸ—“ Updated Jan 2025

🌐 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.
RankOWASP API Top 10 (2023)DescriptionExample
API1Broken Object Level AuthorizationAccessing other users' objects by changing IDGET /api/orders/12346 returns another user's order
API2Broken AuthenticationWeak or absent auth mechanismsNo token expiry, brute-forceable credentials
API3Broken Object Property Level AuthorizationExposing or accepting excessive object fieldsMass assignment enabling role escalation
API4Unrestricted Resource ConsumptionNo rate limits; DoS or cost amplificationFile conversion API called 10M times
API5Broken Function Level AuthorizationAccessing admin endpoints as regular userPOST /api/admin/users accessible without admin role
API6Unrestricted Access to Sensitive Business FlowsAutomating flows meant for human useBulk account creation, inventory clearing bots
API7Server Side Request ForgeryAPI fetches attacker-supplied URLsURL import feature used to reach 169.254.169.254
API8Security MisconfigurationDefault settings, verbose errors, open CORSCORS allows all origins with credentials
API9Improper Inventory ManagementShadow/undocumented APIs in productionOld API version still live and unpatched
API10Unsafe Consumption of APIsTrusting third-party API responses blindlyInjecting 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 MethodUse CaseSecurityComplexity
API KeyServer-to-server, simple integrationsMedium β€” no expiry by defaultLow
JWT (short-lived)Stateless user sessions, microservicesHigh if implemented correctlyMedium
OAuth 2.0 Auth Code + PKCEUser-delegated API accessHighMedium–High
OAuth 2.0 Client CredentialsM2M, service accountsHighMedium
mTLSFinancial, healthcare high-assurance M2MVery HighHigh

🚫 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 ConsiderationRESTGraphQL
Endpoint enumerationDirectory brute force, JavaScript bundle analysisIntrospection query (must disable in prod)
Object authorizationCheck ownership per ID in URL/bodyCheck at resolver level for each field
DoS via expensive queriesPagination limits, response size limitsDepth limits, complexity analysis required
Over-fetching preventionManual response filtering / DTOsInherent β€” client requests specific fields
Schema discoveryOpenAPI spec may be exposedIntrospection exposes full schema
Rate limiting granularityPer-endpointPer-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.

OWASP API Top 10 REST GraphQL OAuth 2.0 JWT Rate Limiting API Gateway Shadow APIs OpenAPI