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

🌐 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.

Recent API Breaches (2024–2025)

  • Salesforce (2024) β€” A vulnerability in the Identity-Qualification (IQ) service allowed attackers to access customer data through API enumeration. Over 100 companies implicated. Demonstrated how a single API logic flaw at the platform scale can compromise an entire ecosystem.
  • Microsoft Entra ID / Dataverse (2024) β€” Token forgery vulnerabilities in Microsoft's identity infrastructure allowed unauthorized access to customer APIs. Showed that even the most mature auth providers can have supply-chain-level API vulnerabilities.
  • DoorDash / Uber driver APIs (2023–2024) β€” Multiple gig economy platforms exposed massive driver data sets through IDOR flaws in their internal APIs. Attackers could enumerate any driver's SSN, bank details, and performance metrics by incrementing API IDs.
  • Chegg, LinkedIn (2022–2023) β€” Customer support APIs exposed student/employee PII through IDOR and missing authentication on lookup endpoints. Demonstrated that internal-facing support APIs are often less protected than consumer-facing ones.
RankOWASP API Top 10 (2023)DescriptionExample
API1Broken Object Level AuthorizationAccessing other users' objects by changing IDGET /api/orders/12346 returns another user's order. Mitigation: check resource ownership in every query; use UUIDs instead of sequential IDs as defense-in-depth
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. Mitigation: use DTOs with explicit field allowlists; annotate models with @JsonIgnore or equivalent to block unauthorized fields
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

🤖 AI/LLM API Security

AI model APIs (OpenAI, Anthropic, local LLMs via vLLM/Ollama) represent a rapidly growing attack surface with unique vulnerabilities. Unlike traditional REST APIs, these systems process natural language inputs that can contain hidden attack payloads β€” making them targets for both classic API attacks and AI-specific threats.

AI-Specific API Threats

  • Prompt injection via API inputs β€” attackers craft API payloads that hijack system prompts, exfiltrate instructions, or bypass content filters. Common in chat, code-generation, and RAG pipelines.
  • Token budget exhaustion β€” malicious or buggy clients chain API calls to generate runaway token consumption, causing unexpected cost spikes (cost amplification). A single user can drain a company's API credits in minutes.
  • Adversarial API abuse β€” using LLM APIs as proxies for spam, phishing, malware generation, or opinion spam. This can get your API key flagged or banned by the provider.
  • System prompt leakage β€” carefully constructed inputs that trick the model into revealing its internal prompt, which often contains instructions about data handling, security rules, and internal processes.
  • Training data extraction β€” attackers query the API repeatedly with adversarial prompts to reconstruct training data, potentially exposing PII or proprietary information baked into the model.
  • Tool/function calling abuse β€” models with function-calling capabilities can be tricked into executing unauthorized operations through adversarial input injection.

Protecting AI APIs

  • Input/output validation β€” sanitize and validate both user inputs and model outputs. Check for prompt injection patterns, unexpected data types, and suspicious output structures.
  • Per-user cost limits β€” enforce daily/monthly API spend caps per user or service account. Alert on anomalous usage spikes.
  • Rate limiting per token budget β€” limit API calls based on expected output length, not just request count. Complex queries that generate large outputs should count more heavily.
  • Separate API keys β€” use dedicated keys for AI access with narrower scopes. Never mix AI API keys with general-purpose API keys.
  • Output filtering β€” scan model responses for PII, internal URLs, or other sensitive data before returning them to callers.
  • Provider terms of service compliance β€” many providers prohibit using their APIs for bulk content generation, training other models, or adversarial testing. Violations can lead to permanent bans.
  • Local model isolation β€” when self-hosting (vLLM, Ollama), treat the inference server as a network service. Enforce mTLS, rate limiting, and access control just like any other API.

AI APIs Are Still APIs

Despite their unique AI-specific vulnerabilities, AI model APIs must also follow all standard API security practices. An LLM API endpoint that lacks rate limiting, authentication, input validation, or proper CORS configuration is vulnerable to both traditional API attacks AND AI-specific ones. Don't let AI security concerns distract from the fundamentals.

🔐 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).
  • Expiry & rotation β€” unlike JWTs, API keys have no built-in expiration. Set a maximum lifetime (e.g., 90 days) and enforce automated rotation. Revoke immediately on suspected compromise. Use key versioning so old keys can be deactivated without re-issuing.
  • Key classification β€” separate production, staging, and development keys. A leaked staging key should not expose production data. Never share keys across environments.

OAuth 2.0 for APIs

  • Authorization Code + PKCE β€” for user-delegated access from SPA or mobile apps. Prevents code interception attacks. Public clients (SPAs, mobile) must use PKCE per RFC 7636.
  • 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). RFC 8705 (DAP) formalizes client authentication via mTLS for OAuth 2.0.
  • Refresh token security β€” implement refresh token rotation (RFC 6819): on each refresh, issue a new token and invalidate the old one. Bind refresh tokens to client identity and IP (when practical). Use a revocation endpoint (RFC 7009). Set finite expiration on refresh tokens (days to weeks, not years) and use sliding expiration.

Zero Trust for APIs

  • Always-verify β€” every request must be authenticated and authorized regardless of whether it originates from inside or outside the network perimeter. The internal network is not a trust boundary.
  • Explicit authorization β€” use attribute-based access control (ABAC) or policy engines (OPA, Casbin) to make fine-grained authorization decisions at the API layer, not just role-based checks.
  • Continuous verification β€” mTLS with short-lived certificates (minutes instead of years) combined with runtime identity validation. Tools like SPIFFE/SPIRE automate this for service meshes in Kubernetes.
  • Least-privilege scope β€” issue scopes and permissions at the granularity of the actual action needed (e.g., `orders:read` not `orders:*`). Audit scope usage to tighten over time.

BFF (Backend-for-Frontend) Pattern

  • Server-side token storage β€” the BFF acts as a proxy between the frontend and APIs. Access tokens and refresh tokens stay server-side; the frontend only receives an httpOnly, SameSite cookie. This prevents XSS-based token theft in SPAs and mobile webviews.
  • Token exchange at the boundary β€” the BFF handles the OAuth/OIDC flow (Auth Code + PKCE) and exchanges the authorization code for tokens server-side. The frontend never sees the user's tokens or client secret.
  • CSRF defense β€” httpOnly cookies with SameSite=Strict (or Lax with CSRF tokens via Double Submit Cookie pattern). Modern browsers' SameSite=Lax default provides decent CSRF protection for cookie-based sessions.
  • Frontend decoupling β€” the BFF can aggregate multiple backend APIs, transform responses for specific device types, and implement per-frontend rate limits without exposing backend topology to the client.
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 accessHigh. OAuth 2.1 (draft) simplifies this by dropping PKCE for browser-based apps and mandating mTLS for public clients.Medium–High
OAuth 2.0 Client CredentialsM2M, service accountsHighMedium
mTLSFinancial, healthcare high-assurance M2MVery HighHigh
Passkeys / WebAuthnPasswordless user API accessHighMedium
SPIFFE/mTLS + short-lived certsService mesh, Kubernetes M2MVery HighHigh

🔓 JWT Security

JWT (RFC 7519) is the most widely adopted token format for API authentication, but it has a history of implementation pitfalls that have led to real-world breaches. Understanding JWT-specific attack vectors is essential β€” many vulnerabilities are not in the JWT spec itself but in how libraries and developers implement verification.

JWT Attack Vectors

  • alg:none bypass β€” some JWT libraries (older versions of jsonwebtoken, PyJWT, spring-joseft) accepted unsigned tokens when the header specified `"alg": "none"`. An attacker can craft a token with no signature and the server treats it as valid. Mitigation: explicitly allow only expected algorithms (e.g., RS256, ES256); never accept "none" in production.
  • Key confusion / algorithm swap β€” when a server verifies with an RSA public key, an attacker can set the token header to `"alg": "HS256"` and use the RSA public key as the HMAC secret. Since the public key is often public, the attack succeeds. Mitigation: enforce a fixed algorithm per token type; never allow the client to influence the `alg` header.
  • Weak signing key brute-force β€” short RSA keys (1024-bit), predictable HMAC secrets (company name + environment), or shared secrets across environments enable offline brute-forcing. The 2021 Auth0 breach was caused by a compromised master signing key β€” attackers forged tokens for any customer tenant. Mitigation: use RSA-2048+ or ES256; rotate keys; never reuse signing keys across environments.
  • Missing claim validation β€” tokens accepted without validating `exp` (expiry), `nbf` (not before), `iss` (issuer), or `aud` (audience) fields. An expired or mis-typed token would still be accepted. Mitigation: validate ALL claims by default; never skip `aud`/`iss` checks even when only consuming a single issuer.
  • JWK header injection β€” adding a `jwk` parameter to the `iss` parameter of a token can trick some libraries into accepting arbitrary public keys as valid. Known to affect Okta, WSO2, and Auth0 in certain configurations. Mitigation: never embed `jwk` in the `iss` parameter; use JWK Set URLs instead.
  • Token storage via XSS β€” storing JWTs in localStorage/sessionStorage exposes them to XSS attacks. An injected script can read and exfiltrate tokens. Mitigation: use httpOnly, Secure, SameSite cookies for web apps, or the BFF pattern for SPAs.

JWT Best Practices

  • Short expiration β€” access tokens should expire quickly (5–15 minutes). Use refresh tokens for longer sessions. Never issue access tokens valid for more than 1 hour.
  • Refresh token rotation β€” (RFC 6819) β€” when a refresh token is used, issue a new one and invalidate the old. This detects replay attacks. Coupled with token binding to the original client/session, rotation makes refresh theft detectable.
  • Token revocation β€” JWTs are stateless by design, which makes revocation difficult. Use a token blocklist (for short-lived tokens), JWKS versioning, or implement RFC 7009 (OAuth 2.0 Token Revocation) for refresh tokens. Redis or a fast store for short-lived blocklists is practical.
  • JWKS caching with timeout β€” cache JWKS responses from the authorization server with a TTL (typically 5–10 minutes). Never cache indefinitely (risk of using revoked keys) and never fetch JWKS on every request (performance + availability). Handle JWKS endpoint failures gracefully with a circuit breaker pattern.
  • Never put sensitive data in JWT payload β€” the JWT payload is Base64-encoded, not encrypted. Anyone with the token can decode and read the payload. Store references (UUIDs) in the token; resolve actual data server-side.
  • Library choice matters β€” prefer well-maintained, widely-audited libraries (e.g., `jose` for Node.js, `pyjwt` with strict config, Nimbus JOSE+JWT for Java). Always pin library versions and audit changelogs for security advisories.
AttackImpactMitigationSeverity
alg:none bypassAccept unsigned tokensExplicitly allowlist algorithms; reject "none"Critical
Key confusion (alg swap)Forge tokens with public keyEnforce algorithm per token type; never trust client algCritical
Weak signing keyOffline brute-forceRSA-2048+ or ES256; unique secrets per envCritical
Missing claim validationExpired/mis-typed tokens acceptedValidate all claims by default; never skip aud/issHigh
JWK header injectionAccept arbitrary public keysNever embed jwk in iss; use JWKS endpointsHigh
XSS token theftClient-side token exfiltrationhttpOnly cookies or BFF pattern; never localStorageHigh

🔒 Data Protection & Privacy for APIs

APIs often serve as the primary vehicle for exposing sensitive personal data. With regulations like GDPR, CCPA, and HIPAA imposing strict requirements on data handling, APIs must be designed with data minimization, protection, and privacy-by-design principles from the start β€” not bolted on after a breach.

Data Minimization Principles

  • Field-level selection β€” clients should only request the fields they need. Server-side, enforce field allowlists per endpoint so no endpoint returns more data than necessary. GraphQL's field selection already enables this; REST needs explicit filtering (DTOs, response serializers).
  • Sensitive data classification β€” label fields by sensitivity (PII, PHI, financial, auth credentials). Apply protection rules per label: mask SSNs, hash emails, redact full credit card numbers. Tools like data classification scanners can auto-detect sensitive fields in response schemas.
  • Context-aware responses β€” a customer-facing API should return different data than an internal admin API for the same resource. Use authorization context to determine what fields to include. An end-user should not see other users' SSNs or internal metadata.
  • Debug vs. production responses β€” debug/error responses frequently leak stack traces, internal field names, database query details, or PII. Strip these automatically in production; never log them to public-facing error output.
  • Default-deny β€” by default, return only fields necessary for the client's declared purpose. If a client doesn't need `user.phone_number`, don't include it in the response β€” even if it's not explicitly "sensitive."

Protecting Data in Transit & Storage

  • Encryption at rest β€” encrypt databases, backups, and file stores containing PII. Use field-level encryption for highly sensitive data (SSN, medical records). Manage encryption keys separately from encrypted data (use KMS, HashiCorp Vault, AWS KMS).
  • Encryption in transit β€” while TLS is standard, ensure HSTS is enabled, use modern TLS versions (1.2+), and disable weak ciphers. For internal API communication, use mTLS.
  • Tokenization β€” replace sensitive data with non-sensitive tokens in API responses and storage. Tokenized data can be used for operations (e.g., payments) without exposing the original value. Use a tokenization service that maintains the token-to-value mapping securely.
  • Data masking in logs β€” API gateway logs, application logs, and debug output must automatically mask sensitive fields. Never log raw credit card numbers, full SSNs, or plaintext passwords. Use log aggregation with automatic PII redaction.
  • Right to erasure (GDPR Art. 17) β€” APIs must support data deletion requests across all systems. Implement a "delete by ID" endpoint that cascades to primary storage, caches, CDNs, and third-party data processors. Log the deletion for audit trails.

Your API Is a Legal Liability

A single API endpoint that leaks user data through over-privileged responses, unvalidated client-side filtering, or debug-mode exposure can result in GDPR fines up to 4% of global annual revenue. Data breaches through APIs are among the most costly and reputationally damaging. Treat API data protection as a legal compliance requirement, not just a technical concern. Implement automated DLP scanning on API responses, and conduct regular privacy impact assessments.

🚫 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.
  • Real-time transports β€” WebSocket and SSE connections need the same authentication and rate limiting as HTTP APIs. Validate origin headers on WS handshakes, enforce message size limits, and be aware that WS connections lack a natural per-request rate limiting boundary.
  • gRPC security β€” gRPC over HTTP/2 inherits HTTP/2 risks (PUSH_PROMISE exploitation, binary metadata attacks). Always use mTLS, set max message sizes, and validate metadata headers just as you would HTTP headers.
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.
  • Schema drift detection β€” use tools like Prisma, Spectral, or Staccato to detect divergence between the OpenAPI spec and the actual production API. Drift breaks security assumptions and creates blind spots.
  • Contract testing (Pact) β€” ensures security invariants (auth requirements, response schemas, error codes) aren't violated across service boundaries during deployments.

Shift-Left: API Security in CI/CD

  • OpenAPI linting in CI β€” run Spectral rulesets against every OpenAPI spec commit to catch security anti-patterns (missing auth, unsafe response schemas, verbose error exposure) before they reach production.
  • Secret scanning in API code β€” integrate truffleHog, git-secrets, or pre-commit hooks to catch API keys, tokens, and passwords committed alongside API code.
  • Infrastructure-as-Code review β€” validate API gateway configurations (Kong, AWS Gateway policies) with tools like checkov or OPA before deploying.
  • Pre-merge auth middleware checks β€” linters or custom scripts can flag endpoints that don't apply auth middleware, ensuring no routes slip through without access control.
  • Dependency scanning β€” API frameworks and their dependencies are frequent targets. Use SCA tools (npm audit, Trivy, Dependabot) to catch vulnerable library versions before they ship.

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.

📊 API Security Monitoring & Observability

Detecting API attacks in real time requires comprehensive monitoring, logging, and anomaly detection. Even the most secure APIs can be misconfigured or targeted by novel attack vectors β€” continuous observability provides the visibility needed to detect, respond to, and learn from attacks.

API Logging & Audit

  • Structured logging β€” log every API request and response in JSON format with: timestamp, caller identity, endpoint, HTTP method, request size, response code, response time, client IP, and user-agent. Avoid plain-text logs that are difficult to parse and analyze at scale.
  • PII filtering in logs β€” never log sensitive data (passwords, tokens, credit cards, SSNs). Implement automatic redaction rules in your logging framework. Log the presence of sensitive fields, not their values (e.g., `"password": ""`).
  • Centralized log aggregation β€” send logs to a SIEM (Splunk, Datadog, ELK) or dedicated API gateway analytics platform. Correlate API logs with infrastructure metrics and WAF events for full-spectrum visibility.
  • Immutable audit trails β€” for regulated industries, store audit logs in tamper-evident storage (WORM storage, blockchain-based logs). Retain for the period required by compliance (typically 1–7 years).

Anomaly Detection & Response

  • Baseline API behavior β€” establish normal request patterns per endpoint (typical frequency, data volumes, time-of-day). Use machine learning or statistical methods to detect deviations in real time.
  • Automated alerting β€” trigger alerts on: unusual data exfiltration volumes (>3Γ— normal), rapid endpoint enumeration (404 spikes), auth failure bursts, geographic anomalies (impossible travel), and API key usage from unexpected locations.
  • OpenTelemetry integration β€” instrument APIs with OpenTelemetry for distributed tracing. Correlate traces across API gateway β†’ backend services β†’ databases to identify the attack surface and impact radius of an incident.
  • Incident response playbooks β€” prepare runbooks for common API incidents: key compromise (revoke + rotate), credential stuffing spike (enable WAF bot rules), data exfiltration (throttle + alert + block), and DDoS (scale + rate limit + CDN).
  • Post-incident analysis β€” every API security incident should result in a written post-mortem with timeline, impact assessment, root cause, and remediation plan. Feed findings back into security testing, monitoring, and architecture improvements.

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