Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 80 ยท Web Application Security

API Security

Secure your APIs: authentication, object-level authorization, rate limiting with a token bucket, mass assignment, excessive data exposure and the OWASP API Top 10.

Modern applications are mostly APIs. The mobile app, the single-page front end, partner integrations and internal microservices all talk to endpoints that return data as JSON. There is no HTML page to hide behind: every route is directly callable by anyone with a script, and attackers do not need your front end at all.

That changes the security picture. A web form limits what a normal user can do by only showing certain buttons, but an API will happily answer any request that is well formed. So the server must enforce every rule itself: who you are, what you may touch, how often you may call, and what fields you may send or receive. This lesson walks through the most common API weaknesses and gives you runnable defenses. It builds on Authorization and Access Control Models and Sessions, Cookies and JWTs.

Why APIs are different

flowchart LR
    C["Client<br/>(app, script, attacker)"] -->|"1. authenticate"| G["API gateway<br/>rate limit, TLS"]
    G -->|"2. authorize every object"| S["Service logic"]
    S -->|"3. filter the response"| C
    S --> D[("Database")]

Three checks guard every call: who are you, may you touch this object, and what may you see.

The OWASP project keeps a separate list for APIs because the failures are different from classic web pages. The 2023 edition names these risks:

  1. Broken object level authorization (changing an ID in the URL to read someone else's data).
  2. Broken authentication.
  3. Broken object property level authorization (excessive data exposure and mass assignment together).
  4. Unrestricted resource consumption (no limits on requests, sizes or costs).
  5. Broken function level authorization (a normal user calling an admin endpoint).
  6. Unrestricted access to sensitive business flows (bots abusing sign-up or ticket buying).
  7. Server-side request forgery.
  8. Security misconfiguration.
  9. Improper inventory management (forgotten old versions and debug endpoints still online).
  10. Unsafe consumption of APIs (trusting data from third-party APIs).

The rest of the lesson takes the most common ones in turn.

Authentication for APIs

Most APIs authenticate every request with a credential in the Authorization header, not a browser session. Common choices are API keys (a long random string identifying an application), bearer tokens such as short-lived JWTs or opaque tokens issued by an identity provider, and OAuth 2.0 when users delegate access (OAuth 2.0, OpenID Connect and SSO). Whatever you choose:

  • Send credentials only over HTTPS, in a header, never in the URL (URLs end up in logs and browser history).
  • Make tokens short-lived and revocable. A leaked token that lives for a year is a long-term breach.
  • Store API keys the way you store passwords: keep only a hash. Because keys are long and random, a fast hash such as SHA-256 is enough, and the plain key is shown to the owner once.
  • Compare secrets in constant time, as in HMAC and Message Authentication.
  • Return the same error for "unknown key" and "wrong key", and throttle failed attempts.
Python Verifying API keys stored as hashes

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 input()), it gets the next line from this box.

If the database leaks, the attacker gets hashes of 192-bit random keys, which cannot be reversed.

Object-level authorization (BOLA)

The number one API risk is simple to describe and very common. The endpoint GET /api/invoices/1042 checks that you are logged in, but not that invoice 1042 is yours. An attacker loops over IDs and downloads everyone's invoices. Hiding the IDs behind random UUIDs makes guessing harder, but it is not a fix: the check invoice.owner == current_user must happen on every access to an object. The same applies to function-level checks: admin routes must verify the role on the server, not rely on the front end hiding the menu.

Rate limiting with a token bucket

Without limits, one client can brute-force passwords, scrape your whole catalog, or run up your cloud bill. Rate limiting caps how often a caller may act. A popular algorithm is the token bucket: a bucket holds at most capacity tokens and refills at rate tokens per second. Each request spends one token. Bursts up to the capacity are allowed, but the long-run average cannot exceed the refill rate. When the bucket is empty the API answers 429 Too Many Requests and, ideally, a Retry-After header.

The demo uses a fake clock so the output is exactly reproducible:

Python A token bucket 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 input()), it gets the next line from this box.

Real deployments keep the counters in a shared store such as Redis so that all servers see the same state, and choose the key carefully: per user for authenticated calls, per IP for anonymous ones. Apply tighter limits to expensive or sensitive routes such as login, password reset and search. Also cap request body size, page size, query depth and file upload size; these are all forms of unrestricted resource consumption.

Mass assignment

Many frameworks can fill an object straight from the request body: user.update(request.json). This is mass assignment. If the user model also has an is_admin or balance field, an attacker simply adds "is_admin": true to the JSON. The fix is an allow-list of fields that clients may set, applied on the server, plus validation of every value.

Excessive data exposure

The opposite problem is returning the whole database row and letting the client choose what to display. The mobile app shows only a name, but the JSON also contains an email, a password hash and an internal note. Anyone using a proxy sees all of it. Define an explicit response schema per endpoint and send only those fields.

Python Allow-list in, allow-list out

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 input()), it gets the next line from this box.

Other habits that matter

  • Validate input against a schema: types, lengths, ranges, enum values (Input Validation and Sanitization). Reject unknown fields rather than ignoring them.
  • Version and inventory your APIs. Retire old versions; a forgotten /v1 without the new checks is a classic back door.
  • Use correct HTTP methods and status codes, and keep error bodies generic. A stack trace in a 500 response helps attackers.
  • Configure CORS narrowly and avoid wildcards on credentialed endpoints (CSRF, SameSite and CORS).
  • Log and monitor authentication failures, 403s and 429s. A burst of 403s on sequential IDs is a BOLA attack in progress.
  • Treat third-party APIs as untrusted input too. Validate what they return and set timeouts.
  • Use the headers from HTTP Security Headers, even on JSON responses (nosniff in particular).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An endpoint returns /api/orders/501 to any logged-in user, whoever owns the order. Which risk is this?

    Authentication proves who you are, but the server must also check that this particular object belongs to you. Missing that check lets attackers iterate over IDs.
  2. 2. A token bucket has capacity 10 and refills 2 tokens per second. A client has been idle for a minute. How many requests can it send at once?

    The bucket never holds more than its capacity, so idle time only fills it to 10. After that burst, the client is limited to the refill rate.
  3. 3. What is the best defense against mass assignment?

    Mass assignment works when the server copies every field it receives. An explicit list of fields clients may set removes the attack.
  4. 4. Why is it acceptable to store API keys with plain SHA-256, while passwords need scrypt or Argon2?

    Slow hashes exist to make guessing low-entropy human passwords expensive. A long random key has enough entropy that guessing is infeasible even with a fast hash.
  5. 5. Which response design avoids excessive data exposure?

    Anything in the response is visible to whoever calls the API, so the server must filter before sending.

Summary

  • Every API request needs authentication, per-object authorization and a filtered response, enforced on the server.
  • Use short-lived, revocable tokens; store API keys as hashes; send credentials only in headers over HTTPS.
  • Rate limit with a token bucket (burst plus steady rate), with stricter limits on login and expensive routes.
  • Defend against mass assignment with writable-field allow-lists and against data exposure with response schemas.
  • Keep an API inventory, validate against schemas, keep errors generic and monitor 403 and 429 spikes.

Next: Networking Essentials for Defenders, where we move from applications down to the network that carries them.