SecurityVol. 10 · Part X
0 / 0

Shelves / Security

SE·110

API Security

Securing APIs end to end: the OWASP API Security Top 10, authentication options (API keys, OAuth tokens, mTLS, request signing such as AWS SigV4 and HTTP Message Signatures), object- and property-level authorisation, schema validation and strict parsing, rate limiting and quotas against abuse, replay protection with timestamps and nonces, idempotency, webhooks, CORS for APIs, gateways, GraphQL and gRPC specifics, and audit logging, in Java, Go, Python, Rust and TypeScript.

29 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: an API is a front door for programs

A web page has a human in front of it; an API has programs, which never get tired, never read warnings and can send thousands of requests a second. API security is therefore about four things: who is calling (chapter 109), what shape of input you accept, how much they may send, and making sure a message can't be forged or replayed.

Accept exactly the shape you expect

A strict schema for "place an order" (item up to 40 characters, qty an integer from 1 to 20, nothing else):

Text
{"item":"dal","qty":2}                → accepted
{"item":"dal","qty":2,"price":0}      → 422 extra_forbidden at ('price',)
{"item":"dal","qty":"2"}              → 422 int_type at ('qty',)
{"item":"dal","qty":500}              → 422 less_than_equal at ('qty',)
{"item":"dal","qty":2,"role":"admin"} → 422 extra_forbidden at ('role',)

If the server bound the request body straight onto its database object, the extra price or role field would be saved: that is mass assignment. Rejecting unknown fields, checking types and enforcing ranges at the boundary removes the problem, and also stops absurd values (500 dishes) before they reach business logic.

Limit how much each caller can send

nginx's limit_req, keyed by API key, at 5 requests per second with a burst of 10:

Text
key A, 40 requests at ~20/s: 200 × 21, 429 × 19   ..............xx.xxx.xxx.xxx.xx.xxx.xxx.
key B right after, 5 requests: 200 × 5            .....

Key A got its burst of about ten, then roughly one request in four (5 per second out of 20). Key B was unaffected, because the limit is per key, not global. A 429 Too Many Requests tells well-behaved clients to back off; limits protect against abuse, scraping, credential stuffing and runaway client bugs alike.

Make messages unforgeable and unrepeatable

A payment provider calls your webhook. The body is signed with HMAC over a timestamp, a nonce and the body:

Text
genuine delivery           : accept
same delivery again        : reject: replayed nonce
body changed (order 102)   : reject: bad signature
captured, sent 10 min late : reject: stale timestamp

The signature proves the sender holds the shared key and nothing changed. The timestamp window (here 5 minutes) and the nonce record stop someone who captured a genuine request from sending it again. The signature is compared with a constant-time function so timing can't leak it byte by byte.

Make retries safe

Text
first attempt (response lost on the network): {'status': 201, 'charge_id': 'ch_1'}
client retries with the same key           : {'status': 201, 'charge_id': 'ch_1', 'replayed': True}
charges actually made: [450]

Networks drop responses, so clients retry. An idempotency key sent with the request lets the server recognise the retry and return the stored result instead of charging twice. It is a correctness feature and a security one: it stops replays turning into duplicate actions.

How deep to go in API security

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Name the OWASP API Top 10 risks and the four concerns: identity, input shape, volume, integrity
L2 Apply strict schemas, per-object authorisation, rate limits and signed webhooks to an API you build
L3 Explain API authentication options, replay protection, idempotency and gateway controls and when each fits
L4 Test an API for authorisation, validation, rate-limit and replay weaknesses and verify the fixes
L5 Design an organisation's API security platform: gateway, policies, key management, abuse detection
L6 Set API security standards, review processes and metrics across many teams and partners

Why APIs need their own chapter

Modern applications are APIs first: web and mobile front ends, partners, internal microservices and AI agents all call them. APIs expose business logic and data directly, without a UI that hides things, and attackers script against them at scale. The OWASP API Security Top 10 (2023) summarises what goes wrong:

# Risk In one line
API1 Broken Object Level Authorization (BOLA) Change an ID, get someone else's data
API2 Broken Authentication Weak token validation, credential stuffing, unprotected login endpoints
API3 Broken Object Property Level Authorization Excessive data exposure in responses; mass assignment in requests
API4 Unrestricted Resource Consumption No limits on rate, size, pagination, expensive operations, paid third-party calls
API5 Broken Function Level Authorization Regular users can call admin endpoints
API6 Unrestricted Access to Sensitive Business Flows Bots buying all tickets, mass account creation, coupon abuse
API7 Server-Side Request Forgery Chapter 108
API8 Security Misconfiguration Verbose errors, permissive CORS, missing TLS, default settings
API9 Improper Inventory Management Forgotten old versions, debug endpoints, shadow APIs
API10 Unsafe Consumption of APIs Trusting third-party API responses without validation

The layers of defence for a request:

client edgeTLS · WAFDDoS · bots gatewayauthN · quotaschema · size serviceauthZidempotency datatenant scopeRLS · KMS audit log · security metrics · alerts (every layer)
Defence layers for an API request. The edge terminates TLS and applies coarse protections; the gateway authenticates, enforces quotas and validates against the schema; the service performs function- and object-level authorisation and business rules; data access is scoped by tenant; every decision is logged for audit. Each layer has a distinct job, and no single one is sufficient.

Authenticating API clients

Mechanism Identifies Good for Caveats
API keys A client application/account Simple server-to-server integrations, public APIs with quotas Bearer secrets; long-lived; no user context
OAuth 2 access tokens Client + (optionally) user, with scopes User-delegated access, partners, SPAs/mobile Validate fully (chapter 109)
Client credentials / workload identity A service Internal and partner machine-to-machine Prefer short-lived tokens, private_key_jwt
mTLS A client certificate Service-to-service, banking (FAPI), B2B Certificate lifecycle management
Request signing (HMAC or asymmetric) Key holder, plus message integrity Cloud APIs (AWS SigV4), webhooks, high-value requests Canonicalisation must be exact

API keys done right

  • Generate with ≥128 bits of randomness; add a recognisable prefix (sk_live_…, ghp_…) so secret scanners (GitHub push protection, Gitleaks) detect leaks.
  • Store only a hash (SHA-256 suffices because keys are high-entropy, unlike passwords) and show the full key once at creation; display only a short suffix later.
  • Scope keys to permissions and environments; support multiple active keys per client for zero-downtime rotation; record last-used time; let customers revoke.
  • Transmit only in headers (Authorization or X-API-Key), never in URLs (logged by proxies and browsers).
// Go: issue and verify API keys by hash lookup
func NewAPIKey() (plain string, hash [32]byte) {
    plain = "sk_live_" + rand.Text()                 // Go 1.24+: 26 base32 chars, 128+ bits
    return plain, sha256.Sum256([]byte(plain))
}

func (s *Store) Authenticate(ctx context.Context, presented string) (*Client, error) {
    h := sha256.Sum256([]byte(presented))
    c, err := s.clientByKeyHash(ctx, h[:])           // indexed lookup by hash
    if err != nil || c.Revoked { return nil, ErrUnauthorized }
    return c, nil
}

Request signing

Signing proves possession of a key and protects the request's integrity (the method, path, selected headers and body can't be altered in transit, even by intermediaries terminating TLS). Examples:

  • AWS Signature Version 4: a canonical request (method, URI, query, signed headers, payload hash) is hashed, combined with date, region and service in a "string to sign", and signed with an HMAC key derived from the secret through a chain of HMACs (date → region → service → aws4_request). The timestamp limits replay to a short window.
  • HTTP Message Signatures (RFC 9421, 2024): a standard way to sign selected HTTP components (@method, @target-uri, content-digest, …) with HMAC or asymmetric keys, with signature parameters (created, keyid, nonce).
  • Webhooks: providers sign payloads (Stripe: t=timestamp,v1=HMAC(secret, t + "." + body)); receivers verify the signature over the raw body bytes and reject old timestamps.

The hard part is canonicalisation: both sides must sign exactly the same bytes. Use SDKs or the standard rather than inventing a scheme, and verify against the raw body before parsing JSON.

Authorisation in APIs

Object-level (BOLA)

Covered in chapter 109: every endpoint that takes an object ID must check the caller may access that object. Defences that scale:

  • Data access through repositories that require a tenant or owner scope.
  • Unpredictable IDs (UUIDv4/v7) reduce enumeration but are not authorisation.
  • Automated tests that call every endpoint as user A with user B's object IDs.

Property-level

Two directions:

  • Responses: don't return whole database entities and rely on the client to hide fields. Map to response DTOs per audience (a public profile vs the owner's view vs admin), so password_hash, internal_notes and other users' emails never leave.
  • Requests: bind input to DTOs with only writable fields (mass assignment, chapter 108).

Function-level

Admin and privileged operations (DELETE /users/{id}, POST /admin/refunds) need role or permission checks on the server, even if "nobody knows the URL". Group them under distinct routes with mandatory middleware, deny by default, and test with non-admin tokens.

Input validation and schema enforcement

Validate at the boundary that requests match a strict contract:

  • Types, formats, ranges, lengths, enumerations, required fields.
  • Reject unknown fields (or at least ignore them explicitly) to prevent mass assignment and parser confusion.
  • Limits: body size, array lengths, string lengths, JSON nesting depth, number of query parameters, file sizes.
  • Canonical forms: normalise Unicode where identity matters (usernames), reject ambiguous encodings, use one JSON parser consistently (different parsers disagreeing on duplicate keys has caused authentication bypasses).

Contracts can be enforced from an OpenAPI schema at the gateway or via middleware, and in code via validation libraries:

// TypeScript: Zod schema, strict (unknown keys rejected), with limits
import { z } from "zod";
const CreateTransfer = z.object({
  fromAccount: z.string().uuid(),
  toAccount: z.string().uuid(),
  amountCents: z.number().int().positive().max(1_000_000_00),
  currency: z.enum(["EUR", "USD", "GBP"]),
  reference: z.string().max(140).optional(),
}).strict();

app.post("/transfers", express.json({ limit: "16kb" }), (req, res) => {
  const parsed = CreateTransfer.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: "invalid_request" });
  // parsed.data is typed and contains only known fields
});

Validation complements, never replaces, parameterised queries, output encoding and authorisation.

Rate limiting and quotas

Unrestricted resource consumption (API4) covers DoS, cost explosions (an endpoint that sends SMS or calls a paid LLM API), scraping and brute force. Controls:

Control Example
Rate limits (requests per time window) 100 req/s per API key; 5 login attempts per minute per account (Vol. 5 ch. 76 for algorithms: token bucket, sliding window, GCRA)
Quotas (usage per billing period) 1M calls per month on the free tier
Concurrency limits Max 10 in-flight exports per tenant
Cost-based limits GraphQL query cost, LLM tokens per minute, weighted endpoints
Size and pagination limits Max page size 100; max upload 10 MB; cursor pagination
Timeouts Server-side deadlines on every request and downstream call
Business-flow limits (API6) One ticket purchase per account per event; CAPTCHA/attestation on sign-up

Key the limits by the right identity (API key, user, tenant, plus IP/ASN for unauthenticated endpoints, recognising IPs are shared and spoofable via X-Forwarded-For unless set by your own proxy), apply them at the gateway and inside services for expensive operations, return 429 Too Many Requests with Retry-After and rate-limit headers (RateLimit/RateLimit-Policy per the IETF draft), and alert on sustained abuse.

Replay protection and idempotency

Replay

An attacker (or a misbehaving proxy) who captures a valid, signed request can resend it. Protections:

  • TLS prevents capture on the wire, but not replay by an endpoint that sees plaintext, or by a client that logged requests.
  • Timestamps: include a timestamp in the signed content; reject requests outside a window (e.g. ±5 minutes; requires reasonably synced clocks).
  • Nonces: include a unique value (jti, nonce) in the signed content; the server remembers recently seen nonces for the window and rejects duplicates.
  • Sender-constrained tokens (DPoP proofs include jti, iat, method and URL).
  • Short-lived tokens limit the replay window for bearer credentials.
Python
# Webhook verification with replay protection (Stripe-style header: t=<ts>,v1=<hex>)
import hmac, hashlib, time

TOLERANCE = 300  # seconds

def verify_webhook(secret: bytes, raw_body: bytes, header: str, seen: "NonceStore") -> None:
    parts = dict(p.split("=", 1) for p in header.split(","))
    ts, sig = int(parts["t"]), parts["v1"]
    if abs(time.time() - ts) > TOLERANCE:
        raise Unauthorized("stale")
    expected = hmac.new(secret, f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        raise Unauthorized("bad signature")
    if not seen.add_if_absent(sig, ttl=TOLERANCE):        # e.g. Redis SET NX EX
        raise Unauthorized("replay")

Idempotency

Replays aren't always malicious: clients retry after timeouts. For non-idempotent operations (payments, orders), accept an Idempotency-Key header and store the first result keyed by (client, key), returning the same result for repeats (Vol. 5 ch. 74). This makes retries safe, and also neutralises duplicate submissions. Security notes: scope keys per authenticated client (so one client can't read another's cached response), bind the key to a hash of the request body (reject reuse with different parameters), and expire keys.

Webhooks (outbound and inbound)

Sending webhooks: sign payloads (HMAC or asymmetric), include a timestamp and event ID, retry with backoff, let customers rotate secrets with overlap, and protect against SSRF: customers choose the destination URL, so validate destinations and send from an isolated egress network (chapter 108).

Receiving webhooks: verify signatures over the raw body, check timestamps and deduplicate by event ID, respond quickly (queue the work), and treat payload contents as untrusted (re-fetch the object from the provider's API if the action matters).

CORS and browsers

Public APIs consumed by browsers need CORS configured with exact origin allow-lists (chapter 108). APIs that use cookies for authentication need CSRF protection; APIs that use Authorization headers don't, but must keep tokens away from XSS. For APIs not meant for browsers, don't enable CORS at all.

API gateways and inventory

An API gateway (Kong, Envoy Gateway, Apigee, AWS API Gateway, Azure API Management, Tyk, Gravitee) centralises cross-cutting controls: TLS, authentication, rate limits, quotas, schema validation, request size limits, logging. Keep authorisation decisions about objects inside services, which know the data.

Inventory (API9): you can't secure what you don't know exists. Maintain a catalogue of APIs and versions (OpenAPI specs in the repository, a developer portal, Backstage), detect shadow APIs from traffic, retire old versions (old /v1 endpoints often lack newer protections), and remove debug and test endpoints from production builds.

Unsafe consumption (API10): validate responses from third-party APIs like any input (schema, size, timeouts), don't follow their redirects blindly, use TLS with verification, and isolate failures (circuit breakers).

GraphQL and gRPC specifics

GraphQL:

  • One endpoint, flexible queries: enforce depth limits, query cost analysis, pagination limits, and persisted queries (allow-listed operations) for first-party clients.
  • Disable introspection in production for private APIs (not a security boundary, but reduces reconnaissance).
  • Authorise in resolvers (or a data layer they all use), per field and per object; a type reachable via many paths is easy to leak.
  • Batching and aliases can multiply operations in one request (login mutation aliased 1,000 times defeats per-request rate limits): count operations, not requests.

gRPC:

  • Use TLS/mTLS (grpc.Creds), authenticate via per-RPC metadata (tokens) or peer certificates in interceptors.
  • Set max message sizes, deadlines and per-method authorisation; reflection disabled in production unless needed.
  • Protobuf parsing is safer than native serialisation, but validate semantics (protovalidate).

Audit logs

Audit logs record who did what to which resource, when, from where, and with what outcome, for security investigation, compliance (SOC 2, ISO 27001, PCI DSS, HIPAA) and customer transparency.

Field Example
Actor user:123 via client:web-app; service identity; impersonation by admin:7
Action invoice.read, user.role.update, apikey.create
Resource invoice:inv_789 in tenant:acme
Outcome allowed/denied, success/failure, reason
Context Timestamp (UTC), source IP, user agent, request ID / trace ID
Change Before/after for sensitive fields (not secrets)

Properties:

  • Structured (JSON) and separate from debug logs, with longer retention.
  • Tamper-evident: append-only storage (S3 Object Lock, WORM), restricted write paths, hash chaining or signed batches; ship off the host quickly (attackers clear local logs).
  • No secrets or excessive personal data: never log passwords, tokens, full card numbers; mask or hash identifiers where possible (Vol. 9 ch. 99).
  • Cover authentication events (logins, failures, MFA changes, password resets), authorisation denials, privilege changes, data exports, configuration and key changes, and admin/support access to customer data.
  • Feed a SIEM with detection rules (impossible travel, spikes in 403s, enumeration patterns, mass downloads) and alert on them (A09: Security Logging & Alerting Failures).
Go
// Go: structured audit event with slog to a dedicated handler/sink
audit.LogAttrs(ctx, slog.LevelInfo, "audit",
    slog.String("actor", p.Subject),
    slog.String("client", p.ClientID),
    slog.String("action", "invoice.export"),
    slog.String("resource", "tenant:"+p.TenantID+"/invoices"),
    slog.String("outcome", "allowed"),
    slog.String("ip", clientIP(r)),
    slog.String("trace_id", trace.SpanContextFromContext(ctx).TraceID().String()),
)

Lab: API defences, measured

Pydantic 2.13, nginx 1.24 and Python models on the lab machine. Each experiment checks a defence you can add to an API you own.

Experiment 1: strict input models

Python
class OrderIn(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    item: str = Field(max_length=40)
    qty: int = Field(ge=1, le=20)
Text
{"item":"dal","qty":2}                → accepted
{"item":"dal","qty":2,"price":0}      → 422 extra_forbidden at ('price',)
{"item":"dal","qty":"2"}              → 422 int_type at ('qty',)
{"item":"dal","qty":500}              → 422 less_than_equal at ('qty',)
{"item":"dal","qty":2,"role":"admin"} → 422 extra_forbidden at ('role',)

The same idea in other stacks: Jackson's FAIL_ON_UNKNOWN_PROPERTIES with a dedicated request DTO in Spring, DisallowUnknownFields() on Go's json.Decoder, #[serde(deny_unknown_fields)] in Rust, Zod's .strict() in TypeScript. Separate input models from persistence entities, so a new column never becomes a writable API field by accident. Add body-size limits too (client_max_body_size in nginx), because a schema check after parsing a 2 GB body is too late.

Experiment 2: per-key rate limiting in nginx

Nginx
limit_req_zone $http_x_api_key zone=perkey:1m rate=5r/s;
limit_req_status 429;
location /api/ { limit_req zone=perkey burst=10 nodelay; root /srv/www; }
Text
key A, 40 requests at ~20/s over 2.1 s: 200 × 21, 429 × 19
key B immediately after, 5 requests:   200 × 5

A real mistake made while building this lab: the first version used return 200 "ok"; in the location and every one of 40 requests succeeded. return runs in nginx's rewrite phase, before the preaccess phase where limit_req lives, so the limit never ran. Serving a real file (or proxying) made it work. The lesson generalises: test that a control actually fires, don't just read the config. Two more details: keying by a client-supplied header lets an attacker rotate made-up keys, so key by the authenticated key or identity (and fall back to IP for anonymous traffic); and send Retry-After so clients back off properly.

Experiment 3: signed, fresh, single-use webhooks

Text
genuine delivery           : accept
same delivery again        : reject: replayed nonce
body changed (order 102)   : reject: bad signature
captured, sent 10 min late : reject: stale timestamp

The signed string is timestamp.nonce.body; signing the body alone would let an attacker attach a fresh timestamp to an old body. This mirrors Stripe's t=…,v1=… scheme and the IETF's HTTP Message Signatures (RFC 9421). Verify on the raw bytes you received, before JSON parsing, since re-serialising changes whitespace and ordering. The nonce store only needs to remember nonces for the length of the timestamp window, so it stays small (a Redis set with a TTL is typical).

Experiment 4: idempotent retries

Text
first attempt (response lost): {'status': 201, 'charge_id': 'ch_1'}
retry, same key             : {'status': 201, 'charge_id': 'ch_1', 'replayed': True}
charges actually made       : [450]

Production details the model leaves out: store the key with a hash of the request body and reject reuse with a different body (422), handle two concurrent requests with the same key with a lock or a unique constraint (one wins, the other gets 409 or waits), and expire keys after a sensible period (Stripe keeps them 24 hours).

Try it yourself

  1. Send {"qty": 2, "qty": 3} (a duplicate key) to your API. Which value does your parser keep, and could a proxy see the other one?
  2. Change the nginx zone key to $binary_remote_addr and see what happens to key B when both clients share one IP.
  3. Extend the webhook verifier to accept two keys during rotation (old and new) and test it.
  4. Fire two concurrent requests with the same idempotency key at a small Flask or Spring endpoint and check that only one charge is recorded.

Revision sheet: API security

Key ideas

  • OWASP API Top 10 (2023): BOLA, broken authentication, broken object property level authorisation, unrestricted resource consumption, broken function level authorisation, unrestricted access to sensitive business flows, SSRF, misconfiguration, improper inventory, unsafe consumption of third-party APIs.
  • Authenticate with OAuth tokens or mTLS; API keys identify clients but are weak secrets on their own. Sign requests (SigV4, RFC 9421) where integrity matters.
  • Authorise every object and every property (what a caller may read and write).
  • Validate strictly: explicit input models, unknown fields rejected, types and ranges enforced, size limits.
  • Limit consumption: per-identity rate limits, quotas, pagination caps, timeouts, query cost limits for GraphQL.
  • Integrity and freshness: HMAC or signatures over timestamp + nonce + raw body; idempotency keys for retries.
  • Gateways centralise authentication, limits and logging, but services still authorise objects themselves.
  • Inventory: know every API and version you expose; retire old ones.

Numbers to remember

  • Lab: 5 r/s with burst 10 let 21 of 40 requests through over 2.1 s; the second key was untouched.
  • Typical webhook freshness window: 5 minutes; idempotency keys kept around 24 hours.
  • 429 Too Many Requests with Retry-After; 422 for validation failures.

Pitfalls

  • Rate-limit config that never runs (nginx return before limit_req); always test that a control fires.
  • Keying limits on a client-chosen header.
  • Binding request bodies onto entities (mass assignment); returning whole entities (excessive data exposure).
  • Verifying webhook signatures on re-serialised JSON instead of the raw body.
  • GraphQL without depth/cost limits; introspection open in production.
  • Forgotten old API versions with weaker checks.

Glossary

  • BOPLA: broken object property level authorisation (reading or writing fields you shouldn't).
  • Token bucket: rate limiter that refills at a fixed rate up to a burst capacity.
  • Replay attack: resending a captured valid request.
  • Idempotency key: client-chosen ID making a request safe to retry.
  • mTLS: both client and server present certificates.