Course contents

12. Security and Identity Lesson 6 of 8

API Security

The OWASP API Top 10 in practice: BOLA, broken authentication, excessive data exposure and mass assignment, per-key rate limits, input validation and TLS.

16 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Every client is effectively a script: the API itself must enforce every rule the app’s screens imply.
  • BOLA (API1) is the most common API flaw: check each object id against the caller in the service that owns it.
  • Harden authentication endpoints (throttling per account and source, MFA or passkeys) and validate every token fully.
  • Decide per field what goes out (response DTOs) and what may come in (input allowlists): excessive data exposure and mass assignment are both API3.
  • A token bucket per API key at the edge stops one caller from consuming shared capacity; TLS belongs on every hop, not just the edge.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

API security is the set of controls that keep an HTTP or RPC API from being used in ways its owners did not intend: reading other people's data, writing fields that should be read-only, impersonating users, or consuming so much capacity that the service fails for everyone. The OWASP API Security Top 10 (2023) is the common reference:

  1. Broken Object Level Authorization (BOLA)
  2. Broken Authentication
  3. Broken Object Property Level Authorization (excessive data exposure + mass assignment)
  4. Unrestricted Resource Consumption
  5. Broken Function Level Authorization
  6. Unrestricted Access to Sensitive Business Flows
  7. Server Side Request Forgery (SSRF)
  8. Security Misconfiguration
  9. Improper Inventory Management
  10. Unsafe Consumption of APIs

Why it exists

Web pages used to hide most of the logic on the server. Modern apps push rendering to the client and expose objects and functions through APIs, which are easy to call with a script. The app's screens may only show your own orders and only the name field, but the API answers anything that is well-formed. Any rule the API does not enforce does not exist. Attackers also need only a normal account: most of the top risks are abuses of authorized access, not break-ins.

How it works

Object-level authorization (API1). Every id in a path, query or body is attacker-controlled. The service that loads the object checks it against the caller (owner, tenant, team) and answers 403 or 404. Make it structural: a repository method that always filters by tenant, or row-level security in the database, rather than a check each handler must remember.

Authentication (API2). Throttle and monitor login, password reset and token endpoints per account and per source; prefer passkeys or MFA; check passwords against breach lists. Validate tokens fully: signature with a pinned algorithm, iss, aud, exp. Do not put long-lived API keys in URLs (they end up in logs) or in mobile app binaries.

Property-level authorization (API3). Responses go through an explicit output model with an allowlist of fields; never serialize the database row. Requests bind to an explicit input model; never bind the body onto the persistence model. Decide per field whether this caller may read or write it (users may change name, not role).

Resource consumption (API4). A token bucket per API key or per user at the edge; separate, tighter limits on expensive or sensitive operations (login, exports, search); maximum page sizes, request body sizes, upload sizes, query depth for GraphQL, and timeouts. Return 429 with Retry-After.

Function-level authorization (API5). Admin and internal endpoints check roles on the server, not by being hidden from the UI. Deny by default.

Input validation. Validate against a schema (OpenAPI or JSON Schema) at the edge: types, lengths, formats, enums, and additionalProperties: false. Validate again in the service. Validation is about shape; it does not replace authorization. Use parameterized queries regardless.

Transport. TLS 1.2 or 1.3 everywhere, HSTS on browser-facing hosts, and encryption on internal hops too (re-encrypt from the gateway, or mTLS in a mesh; see Zero Trust).

When to use it

Always, for any API reachable by anything you do not fully control: public APIs, mobile and SPA backends, partner APIs, and internal APIs (internal callers get compromised too).

When not to

No API is exempt. What varies is depth: an internal read-only metrics endpoint needs less than a payments API. Avoid controls that only look like security: obscurity (undocumented endpoints), client-side checks, and IP allowlists as the only control.

Trade-offs

Choice You gain You pay
Schema validation at the gateway Junk rejected early, one place to enforce shape Schemas must stay in sync with the service
Per-key limits at the edge Abuse rejected before it costs capacity Picking limits per plan, shared state across gateway nodes
Response DTOs instead of serializing models No accidental field leaks More mapping code
Row-level security in the database Tenant isolation even when code forgets Harder debugging, query planning surprises
Returning 404 instead of 403 Hides which ids exist Harder for legitimate clients to debug

Alternatives

There is no alternative to authorization and validation, but there are choices of where and how: an API gateway versus a service mesh versus in-process middleware for edge checks; policy engines (OPA, Cedar) versus code for authorization; a WAF or bot-management product in front of the gateway for volumetric and known-signature attacks (useful, but it cannot see BOLA or mass assignment, which look like normal traffic).

Failure modes

  • Only the gateway checks: object and field rules need business data the gateway does not have.
  • Old versions left running (API9): /v1 without the fixes that /v2 has, or a forgotten staging host with production data.
  • Global-only rate limits: one client exhausts the shared budget and legitimate users get 429s.
  • Limits per IP only: botnets and cloud ranges spread requests below the limit.
  • Verbose errors: stack traces and "user not found" vs "wrong password" help attackers.
  • SSRF (API7): an endpoint that fetches user-supplied URLs reaches internal metadata services. Allowlist destinations.
  • Trusting third-party APIs (API10): data from partners is input too; validate it.

In production

Keep an inventory of every API, version, host and owner, generated from code or gateway configuration. Generate schemas from code and test that unknown fields are rejected. Write authorization tests that try another tenant's ids on every endpoint. Log authorization failures and alert on spikes (enumeration shows up as many 403/404s from one caller). Rate limit with distributed counters (Redis or the gateway's built-in store), and return Retry-After. Run dependency and configuration scanning in CI, and turn off debug endpoints and CORS wildcards in production.

Common misconceptions

  • "Authenticated means authorized." A valid token says who is calling, not whether they may touch object 1002.
  • "The app only calls endpoints the right way." Attackers call your API without your app.
  • "HTTPS makes the API secure." TLS protects data in transit; it does nothing against a valid user asking for someone else's data.
  • "A WAF covers the OWASP API Top 10." WAFs catch signatures and volume. Most API flaws are logic flaws that look like normal requests.
  • "Rate limiting is a performance feature." It is also a security control against scraping, stuffing and cost attacks.

Interview angle

Interviewers want controls placed in a design, not a list recited. Say where tokens are validated, where object-level checks live, how responses are shaped, and how limits are keyed (per API key, per user, per endpoint cost). Mention BOLA by name, explain mass assignment, and show you know a WAF is not enough. Bonus points for structural fixes: tenant-scoped repositories, row-level security, generated schemas, and authorization tests across tenants.

Model assumptions

Steps 2–5 and 8 are a scripted illustration, not a simulation: object ids, response fields, schemas and credentials are drawn as hand-placed packets with illustrative durations (12 ms to the gateway, 4 ms between internal components). Steps 1, 6, 7 and 9 use the simulation: app users at 100 requests per second and an attacker at 600 requests per second from step 6 (Poisson arrivals), a gateway with 1 ms of work, an orders API with 16 workers, 30 ms mean service time (lognormal, cv 0.3) and room for 40 waiting requests, and a database with 24 connections and 5 ms reads. The API holds a worker for about 37 ms per request, so it serves roughly 430 requests per second; beyond that its queue fills and it answers 503. The per-key limit is a token bucket of 10 requests per second with a burst of 20, drawn as its own lane in front of the gateway because the engine's gateway has a single shared bucket. Numbers are illustrative, not benchmarks of any product.

The lesson as textEvery step of the simulation, written out.
  1. 1. An API hands out objects and functions directly

    App users send 100 requests per second through the API gateway to the orders API. The mobile app only shows what its screens need, but the API answers anyone who speaks HTTP: every endpoint, every id, every field is reachable with a script.

    The OWASP API Security Top 10 (2023) lists what goes wrong most: broken object-level authorization, broken authentication, broken object *property*-level authorization (excessive data exposure, mass assignment), unrestricted resource consumption, broken function-level authorization, and more. This lesson walks through the top four with an attacker who has a normal, valid account.

    Scene: App users send 100 requests per second through the gateway to the orders API and its database. An attacker with a valid account sits next to them, able to call the same API directly.

    Key idea: Assume every client is a script: the API itself must enforce every rule.

  2. 2. API1: walking through other people’s orders

    The attacker requests GET /orders/1001, /1002, /1003. The gateway sees a valid token with the orders:read scope; the API loads each order and returns it, without asking whose it is. Three requests, three strangers’ orders. This is a scripted illustration.

    This is broken object-level authorization (BOLA), number one on the list since 2019. Random UUIDs make guessing harder but are not a fix: ids leak through URLs, logs and shared links. The fix is a per-object check in the service that owns the data, covered in depth in *Authentication vs Authorization*.

    Scene: The attacker requests three consecutive order ids. Each request passes the gateway, the API loads the order from the database and returns it, although none belong to the attacker.

    Key idea: Every object id in a request is attacker-controlled input: check it against the caller, every time.

  3. 3. API2: credential stuffing against /login

    Passwords leaked from other sites are tried against POST /login, thousands per minute. Most fail; people reuse passwords, so some succeed. In the scripted run, three attempts fail and the fourth gets a session.

    Broken authentication covers this and its cousins: no throttling or lockout on login and password reset, tokens accepted without checking signature, exp or aud, long-lived API keys in URLs, and secrets in mobile apps. Defences: passkeys or MFA, breached-password checks, throttling per account and per source, and strict token validation.

    Scene: The attacker tries leaked passwords against the login endpoint. Three attempts are rejected; the fourth succeeds and returns a session.

    Key idea: Authentication endpoints are the most attacked endpoints: throttle them and validate every token fully.

  4. 4. API3: too many fields out, too many fields in

    The attacker calls GET /users/me. The API serializes the whole database row: name, but also email, passwordHash, role and internalNotes. The app shows only the name; the raw JSON shows everything. That is excessive data exposure.

    Then PATCH /users/me with {"name":"x","role":"admin"}. The API binds the request body straight onto the user model and saves it: the attacker is now an admin. That is mass assignment. OWASP 2023 merges both into broken object property level authorization: which *fields* may this caller read or write?

    Scene: The attacker reads their own profile and receives every column, including the password hash and role. A second request sets role to admin, and the API saves it.

    Key idea: Never serialize or bind whole models: decide per field what goes out and what may come in.

  5. 5. Validate input at the edge, shape output in the service

    The gateway now validates requests against the API’s OpenAPI schema: types, lengths, formats, allowed enum values, and additionalProperties: false. The role field is not in the PATCH /users/me schema, so the request is rejected with 400 at the gateway and never reaches the API.

    The service still validates too (the gateway is not the only way in) and maps responses through an explicit response DTO with an allowlist of fields. GET /users/me now returns name and email, nothing else. Validation is about structure; whether *this* caller may change *this* field is still an authorization decision in the service.

    Scene: The attacker’s request to set their role is rejected by the gateway’s schema check with 400 before it reaches the API. A profile read still works and returns only the allowed fields.

    Key idea: Allowlist inputs against a schema and outputs through a DTO; reject unknown fields.

  6. 6. API4: one client eats the capacity

    At 1 s the attacker starts scraping /orders (or running credential stuffing at scale) at 600 requests per second with a valid API key. The orders API serves about 430 requests per second; together with the users’ 100 that is far too much.

    Workers fill, the wait queue fills, and the API answers 503 to whoever arrives at the wrong moment: the users’ requests fail as often as the attacker’s, and the ones that succeed wait in line. This is unrestricted resource consumption: no limit on how much one caller may take.

    Scene: After one second the attacker sends 600 requests per second. The orders API saturates, its queue fills, and requests from app users fail along with the attacker’s.

    Key idea: Without per-caller limits, the noisiest client decides everyone’s latency and error rate.

  7. 7. A token bucket per API key at the gateway

    The gateway keeps a token bucket per API key: this key may send 10 requests per second, with bursts of 20. The scene draws the attacker’s bucket as its own lane in front of the gateway. Everything beyond the budget is answered 429 Too Many Requests at the edge, before it costs the API anything.

    The users’ traffic flows through untouched: their errors drop to zero and latency returns to normal, while about 98% of the attacker’s requests are rejected. Per-key limits are the baseline; add per-account limits on login, cost-based limits on expensive endpoints (exports, searches), pagination caps and request size limits. The *Rate Limiting* lesson covers bucket sizing and global limits.

    Scene: The attacker’s requests now pass a per-key token bucket in front of the gateway. Almost all are rejected with 429 there; app users’ requests reach the API without errors at normal latency.

    Key idea: Limit per caller, at the edge, so abuse is rejected before it reaches shared capacity.

  8. 8. Where each control lives, and TLS on every hop

    One legitimate request, end to end, with the controls named. Edge (gateway): TLS 1.3 termination with HSTS, token validation (signature, iss, aud, exp), schema validation, size limits, per-key rate limits. Service: object-, property- and function-level authorization, output DTOs, business-flow limits. Data: least-privilege database credentials, row-level security for multi-tenant data.

    TLS does not stop at the gateway: tokens and personal data travel on the internal hops too, so re-encrypt (or use mTLS) to the service and the database. Plus the things no diagram shows: an inventory of every API version and host (retire old ones), and logging of authorization failures. This step is a scripted illustration.

    Scene: A user’s request travels over TLS to the gateway, then over encrypted internal hops to the API and the database and back. Each layer is labelled with the controls it enforces.

    Key idea: Coarse, cheap checks at the edge; fine-grained checks next to the data; encryption on every hop.

  9. 9. An API is only as safe as its least checked endpoint

    Check every object id against the caller (API1), harden authentication endpoints and validate tokens fully (API2), decide per field what goes out and what may come in (API3), and limit what each caller may consume (API4). Validate input against a schema, shape output explicitly, encrypt every hop.

    The simulation keeps running with the attacker still at 600 requests per second: the per-key limit absorbs it at the edge.

    Scene: App users send 100 requests per second without errors while the attacker’s 600 requests per second are rejected at the per-key limit.

    Key idea: Authorize objects and fields in the service, validate and limit at the edge, encrypt everywhere.