Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 53 ยท Web Application Security

API Security Testing and Hardening

Learn the OWASP API Top 10 themes, broken object-level authorization, mass assignment, rate limiting and schema validation, with runnable limiter and allow-list models.

Modern applications are built from APIs: the mobile app talks to one, the single-page front end talks to one, and partners and other services call them too. An API has no page layout to hide behind. It exposes data and actions directly as endpoints, and attackers can call them straight from a script. Many of the biggest data leaks in recent years came from API endpoints that returned too much, accepted too much, or never asked whose data was being requested.

This lesson covers the themes of the OWASP API Security Top 10, then looks closely at three of them: broken object-level authorization, mass assignment and missing rate limits. Real APIs and gateways cannot run on this site, so real configuration is read-only. The runnable parts are stand-ins: a sliding-window rate limiter and a field allow-list in Node.js, using made-up data. They show the logic, not a production gateway.

Why APIs are different

Direct access No page hides the endpoints.
Raw data JSON often carries more than needed.
Automation Scripts can call it thousands of times.

Assume every request is crafted by hand.

1 / 2

The OWASP API Security Top 10

OWASP publishes a separate list for APIs, since their risks differ from those of web pages. Editions change the order and names, so use the themes rather than the numbers:

  • Broken object-level authorization (BOLA): an endpoint takes an object ID and does not check that the caller may access that object. It is the same bug as IDOR, described in Authentication, Sessions and Access Control Flaws, and it is the most common serious API flaw.
  • Broken authentication: weak tokens, no rate limit on login, keys in URLs.
  • Broken object property-level authorization: the API returns or accepts fields the caller should not see or change. This covers excessive data exposure and mass assignment.
  • Unrestricted resource consumption: no limits on request rate, page size, upload size or expensive operations.
  • Broken function-level authorization: ordinary users can call admin endpoints (DELETE /users/5).
  • Unrestricted access to sensitive business flows: abuse of legitimate features at scale, such as bulk ticket buying.
  • Server-side request forgery: see SSRF, Path Traversal, Deserialization and Upload Risks.
  • Security misconfiguration: permissive CORS, verbose errors, missing TLS.
  • Improper inventory management: forgotten old API versions and test endpoints still reachable.
  • Unsafe consumption of other APIs: trusting data that arrives from third-party services.

Broken object-level authorization

In an API the object ID is usually in the path (GET /api/orders/812) or in the body. Every endpoint that takes an ID needs the question "may this caller access this object?" answered on the server. Switching to GUIDs makes guessing harder, but identifiers leak in emails, logs and shared links, so unguessable IDs reduce risk without removing the need for the check.

Good patterns include scoping the query to the caller (WHERE id = ? AND account_id = ?), using a policy layer that every controller must call, and writing automated tests that call each endpoint as user A with user B's IDs and expect a 403 or 404. The runnable IDOR example in the previous lesson on sessions and access control shows the vulnerable and fixed shape.

Mass assignment

Frameworks make it convenient to copy a request body straight into a model: User.update(request.body). If the body contains a field the developer never meant to expose, such as role, is_admin, balance or account_id, the client can set it. This is mass assignment (also called over-posting or autobinding). The reverse problem, returning whole database rows to the client, leaks fields like password_hash or internal flags.

The cure is the same on both sides: use an explicit allow-list of fields. Laravel calls it $fillable, Rails strong parameters, and DTO classes or response serializers do the same job. Never rely on a blocklist of "dangerous" fields, because new fields get added and forgotten.

The model below applies a profile update to a fake user, first with a naive copy and then with an allow-list that also validates types and lengths.

Node.js Mass assignment and a field allow-list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The naive version lets the client make themselves an admin with a large balance. The safe version applies the valid name, refuses role and balance, rejects the bad email, and reports the problems. Choosing whether to reject the whole request or to ignore unknown fields is a policy decision. Rejecting makes mistakes and probing visible in logs, which helps detection. Note also the last lines: the response is built from a short list of public fields instead of returning the stored object.

Schema validation

Beyond individual fields, validate the whole request against a schema: types, required fields, string lengths, numeric ranges, enum values, array sizes and maximum body size. OpenAPI or JSON Schema documents can drive this automatically in a gateway or middleware. Validation fixes a lot at once: oversized input, unexpected types that crash parsers, and injection payloads where a number was expected. It also supports resource limits, such as a maximum page size of 100 on list endpoints, so one call cannot request a million rows. Schema checks complement, and never replace, authorization and parameterized queries (see SQL Injection).

Rate limiting

Without limits, an API invites password guessing, scraping, enumeration of IDs and plain overload. A rate limiter counts requests per key (an API key, user ID or IP address) over a time window and answers 429 Too Many Requests when the budget is spent, usually with a Retry-After header. Different endpoints deserve different budgets: a login or password-reset endpoint needs far stricter limits than a read-only listing.

The stand-in below implements a sliding-window log limiter. It takes explicit timestamps instead of the real clock, so the run is deterministic.

Node.js Sliding-window rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A fourth call from the same address within ten seconds gets 429 and a Retry-After value, while a different address is unaffected. After the oldest hit leaves the window, the client may try again. Real systems share this state between servers (often in a fast store such as Redis), pick the key carefully (an attacker can rotate IP addresses, so also limit per account), and combine limits with lockouts and monitoring, as in Password Attacks and Defenses.

Real vs stand-in. The limiter and allow-list above are teaching models. In production, use your framework's maintained rate-limiting middleware or an API gateway, and keep the state shared and expiring. Never write security parsers or validators from scratch if a tested library exists.

Testing an API in an authorized engagement

An authorized API test usually starts from the API's own description (an OpenAPI file or a recorded collection of requests) and checks each endpoint along the same few lines:

  • Call every endpoint without credentials, as a normal user and as another user, with the other user's IDs.
  • Send extra fields, wrong types, huge values and nested objects, and look at how errors are reported.
  • Read responses for fields that the client does not need.
  • Check limits on login, resets, search and any costly operation, within the agreed test windows and load limits in your scope document (see Law, Scope and Rules of Engagement).
  • Look for old versions (/v1/) and undocumented routes still deployed.

Testing proxies and API clients do this work in practice. Run them only against your own lab or in-scope targets, and describe each finding with reproduction steps and a fix in the report. Network and wireless defenses, which protect the traffic these APIs travel on, come next in Network Attacks and How to Defend Against Them.

API key security

An API key identifies and sometimes authorizes a calling application. The two classic failures are hardcoded keys (committed to a repository, baked into a mobile app or shipped in front-end JavaScript, where anyone can read them) and keys with no expiration that live for years and are never rotated, so a leak stays useful forever. Related mistakes: one key with all permissions, keys in URLs (they land in logs and browser history), and the same key for development and production.

Fix: keep keys in a secrets manager or environment variables, never in source control; give each key the minimum scope and, where possible, an IP or referrer restriction; rotate on a schedule and immediately after exposure; support multiple active keys so rotation causes no outage; monitor usage for spikes; and scan repositories for leaked secrets. Remember that an API key is not user authentication: use OAuth tokens for user-level access. See secrets in code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An endpoint GET /api/orders/812 returns order 812 to any logged-in user. Which API risk is this?

    The server authenticates the caller but never checks that the order belongs to them.
  2. 2. What is the safest way to prevent mass assignment?

    Blocklists miss new fields. An allow-list is explicit and fails closed.
  3. 3. A client receives 429 with a Retry-After header. What happened?

    429 Too Many Requests means the request budget for that window was used up.
  4. 4. Why are GUID identifiers not a complete fix for BOLA?

    Unguessable IDs reduce enumeration, but anyone who learns an ID could use it if the server does not check ownership.
  5. 5. Why should responses be built from an explicit list of public fields?

    Returning whole stored objects exposes properties the client was never meant to see.

Summary

  • APIs expose data and actions directly, so every request must be treated as hand-crafted.
  • The OWASP API Top 10 highlights object-level and function-level authorization, property-level exposure, resource limits and inventory problems.
  • BOLA is stopped by ownership checks on every object access, backed by tests that call endpoints with another user's IDs.
  • Mass assignment and excessive data exposure are prevented with allow-lists for input and output fields.
  • Validate whole requests against a schema, including sizes and ranges.
  • Rate-limit by key and endpoint, return 429 with Retry-After, and use stricter limits on login and reset flows.
  • Test only inside an authorized scope.

Next: Network Attacks and How to Defend Against Them.