Guides

Security Guide

API Protection at the Edge: A Practical Configuration Guide

Put the right checks close to the caller, but keep application authorization and business rules where the data and transaction context exist.

APIs connect browsers, mobile applications, partners, internal services, and automation. They also expose precise operations that attackers can repeat at high speed. If an API is reachable from the public internet, a secure design must assume that requests will be malformed, replayed, unauthorized, automated, and intentionally expensive.

Edge protection helps by rejecting clearly invalid or abusive traffic before it consumes origin resources. It does not replace secure application code. The most reliable configuration divides responsibilities: the edge handles transport, coarse filtering, authentication signals, schema and size checks, quotas, and visibility; the application remains the authority for object access, business logic, and data decisions.

This guide is a provider-neutral starting point for REST, JSON, GraphQL, and similar HTTP APIs.

Define the API threat model

Begin with an inventory, not a rule template. Record every public hostname, version, method, route, authentication method, owner, data classification, dependency, and expected client. Include undocumented routes, debug endpoints, old versions, webhooks, GraphQL introspection, and management APIs. OWASP identifies improper inventory management as a major API risk because forgotten hosts and versions remain reachable after teams stop monitoring them.

Map the important threats:

  • Broken object or function authorization that exposes another user's data or an administrative action.
  • Broken authentication, token replay, weak key handling, and credential stuffing.
  • Unrestricted resource consumption through large payloads, expensive queries, or high request volume.
  • Injection, unsafe deserialization, and malformed content that reaches parsers or downstream services.
  • Server-side request forgery and unsafe consumption of third-party API responses.
  • Data leakage through verbose errors, excessive fields, or debug responses.

The edge cannot see every business decision

An edge gateway can verify a token and reject an invalid shape, but it cannot safely decide whether user A may access object B unless the authorization context is designed and enforced by the application or a trusted authorization service.

Configure the edge in layers

1. Establish a trusted transport

Serve the API over HTTPS and define which TLS versions, hostnames, methods, and content types are accepted. Redirecting an API request to an HTML page can break clients and obscure failures, so use an explicit API error contract. Reject unexpected hosts and methods early. Apply request header, URI, body, and query limits before expensive parsing.

For service-to-service or partner APIs, consider mutual TLS, signed requests, or another proof of client possession. For user-facing APIs, use a standards-based token protocol and verify signature, issuer, audience, expiry, not-before, and key rotation state at the appropriate layer. Never treat an API key, source IP, or client-provided identity header as proof of end-user authorization.

2. Validate the request shape

Use the versioned API schema as an allowlist. Validate method, path, query parameters, headers, content type, encoding, field types, string lengths, numeric ranges, nesting depth, and maximum body size. Reject unexpected fields where mass assignment would be dangerous. For GraphQL, cap query depth, aliases, complexity, and batch size according to the service's actual needs.

Validate responses too when practical, especially for sensitive data and partner contracts. A schema check does not make an input safe by itself: the application still needs context-aware output encoding, parameterized queries, safe file handling, and downstream validation.

3. Add quotas and abuse controls

Apply rate limiting by more than IP. Combine source, authenticated principal, API key, route, resource, and operation cost where those identifiers are trustworthy. Give expensive endpoints smaller budgets than cheap reads. Protect login and password reset with separate failure limits. For paid downstream calls, set a service-wide budget as well as per-client quotas.

Return 429 Too Many Requests for an exhausted request budget when the client can retry. Use Retry-After when the retry time is meaningful and document backoff and idempotency behavior. Do not reveal which internal counter triggered the decision. A quota is not a substitute for authorization, CSRF protection where applicable, or transaction limits.

4. Add targeted threat detection

Use a WAF for broad protocol and attack-pattern coverage, and bot management for automation patterns. Tune rules to the API rather than copying browser rules onto machine clients. Allow documented partners through explicit identity and scope, not a permanent IP bypass. Consider anomaly signals such as rapid account changes, many identities from one client, repeated invalid tokens, unusual geographies, and a sudden increase in expensive operations.

5. Preserve origin trust

The origin should accept traffic only from the intended gateway or private path, with a cryptographic or network control that an attacker cannot simply copy into a direct request. Validate forwarded headers at the trusted boundary and prevent callers from spoofing the original client IP, scheme, or host. The companion guide How to Hide and Protect Your Origin Server covers this boundary in detail.

Log decisions, not secrets

For every request, capture a request ID, timestamp, route, method, status, latency, authenticated principal or pseudonymous client ID, policy decision, rule version, and upstream result. Record the reason category, such as invalid token, schema failure, quota, or WAF match. Do not log access tokens, API keys, passwords, full payment data, or sensitive payloads. Hash or redact identifiers according to the investigation need and retention policy.

Create alerts for authentication failures, authorization denials, schema rejection, 429 rates, error changes by API version, unusual data volume, and origin latency. Correlate edge logs with application and dependency logs so a blocked request can be distinguished from an origin failure. Test that logs remain available during an attack and that time synchronization is reliable.

Safe rollout sequence

  1. Inventory hosts, routes, clients, versions, and ownership.
  2. Run schema, authentication, and WAF rules in report-only mode where supported.
  3. Replay representative tests from browsers, mobile apps, partners, jobs, and failure cases.
  4. Enforce transport and size controls first, then authentication and schema checks, then quotas and behavioral rules.
  5. Canary one version or route and compare success, latency, 4xx, 5xx, 429, support, and dependency metrics.
  6. Remove obsolete routes and temporary exceptions only after confirming traffic has migrated.

Avoid these configuration traps

  • Assuming a valid JWT proves access to every object named in the URL.
  • Accepting any Origin, wildcard CORS with credentials, or a reflected CORS value.
  • Allowing undocumented API versions because they still appear in old client code.
  • Parsing huge bodies or deeply nested queries before enforcing size and complexity limits.
  • Putting secrets in URLs, logs, error messages, or cacheable responses.
  • Letting the edge and application disagree about the client identity or request scheme.
  • Deploying a strict policy without a rollback, a canary, and a test client matrix.

Read Rate Limiting Explained, Bot Traffic vs Human Traffic, and the security headers checklist to complete the surrounding controls.

Authoritative references

There are only two hard things in Computer Science: cache invalidation and naming things.

Secure your API entry points

Talk to our team about a practical edge and origin control plan for your APIs.

Contact Optimi