At a glance
What you need
- An API you build or maintain (REST or GraphQL)
- Access to its code and gateway or server configuration
- A test account for two different users
APIs now carry most of the traffic of modern applications, and attackers know it. They skip the web page and call your API directly, changing one ID at a time, asking for fields the app never shows, or calling it a million times. This guide walks through the risks in the OWASP API Security Top 10 and the fixes that stop them.
🔑
Authorize every object
Not just "is this user signed in?", but "may this user touch this record?"
📏
Return and accept only what is needed
Explicit fields in, explicit fields out.
🚦
Limit and inventory
Rate limits on everything, and a list of every API you run.
The OWASP API Security Top 10 (2023)
- Broken object level authorization. Changing an ID returns someone else's data.
- Broken authentication. Weak tokens, no limit on guessing, tokens that are never checked properly.
- Broken object property level authorization. The API returns or accepts fields the caller should not see or set.
- Unrestricted resource consumption. No limits on requests, page sizes, uploads or costly operations.
- Broken function level authorization. Ordinary users can call admin endpoints.
- Unrestricted access to sensitive business flows. Bots buy all the tickets or create thousands of accounts.
- Server-side request forgery. The API fetches a web address the attacker chose, including internal ones.
- Security misconfiguration. Verbose errors, permissive CORS, missing TLS, debug endpoints.
- Improper inventory management. Old versions and forgotten test APIs still running.
- Unsafe consumption of APIs. Trusting what third-party APIs send back without checking it.
1. Check access to every object (API1 and API5)
Broken object level authorization (often called BOLA, or IDOR) has been the top API risk in every edition. The API checks that the caller is signed in, then trusts the ID in the request.
❌ Any signed-in user can read any order
app.get('/api/orders/:id', requireLogin, async (req, res) => {
const order = await Order.findById(req.params.id);
res.json(order);
});
✅ The query itself is scoped to the caller
app.get('/api/orders/:id', requireLogin, async (req, res) => {
const order = await Order.findOne({ _id: req.params.id, customerId: req.user.id });
if (!order) return res.status(404).end();
res.json(toPublicOrder(order));
});
- Scope queries to the caller (or their tenant) in one shared place, such as a repository layer or a database row-level security policy, rather than in each handler.
- Answer
404for records the caller may not see, so IDs cannot be probed. - Random IDs (UUIDs) make guessing harder, but they are not access control.
- Deny admin functions by default and check roles on the server for every route, not just in the menu.
- Write tests with two users: user B must never read or change user A's records.
2. Get tokens right (API2)
JSON Web Tokens (JWTs) are everywhere, and so are mistakes in checking them. Follow RFC 8725, the JWT best current practices:
- Pin the algorithm. Accept only the one you issue (for example
RS256orEdDSA). Never acceptnone, and never let the token's header choose between a public-key and a shared-secret algorithm. - Check every claim: signature, expiry (
exp), issuer (iss) and audience (aud), so a token for one service cannot be used at another. - Keep access tokens short-lived (minutes) and rotate refresh tokens, so a stolen token is soon useless.
- Use a maintained library and its verify function, never a hand-written decoder.
- Limit sign-in attempts, password reset requests and one-time code checks per account and per address.
import jwt # PyJWT
claims = jwt.decode(
token,
public_key,
algorithms=["RS256"], # never taken from the token
audience="https://api.example.ca",
issuer="https://auth.example.ca",
options={"require": ["exp", "iss", "aud", "sub"]},
)
3. Control the fields that go in and out (API3)
Two mirror-image mistakes. Excessive data exposure: the API returns the whole database row, including fields the app hides, such as other customers' email addresses or internal flags. Mass assignment: the API saves whatever fields the request sends, so a user adds "role": "admin" or "price": 0.
❌ Every field in, every field out
await User.updateOne({ _id: req.user.id }, req.body);
res.json(await User.findById(req.user.id));
✅ An explicit list both ways
const { displayName, language } = ProfileUpdate.parse(req.body); // schema validation
await User.updateOne({ _id: req.user.id }, { displayName, language });
res.json(toPublicProfile(await User.findById(req.user.id)));
Define request and response schemas (OpenAPI, Zod, Pydantic, DTO classes) and validate against them. Reject unknown fields rather than silently ignoring them, so mistakes show up in testing.
4. Limit everything that costs you (API4 and API6)
- Rate limits per user, per token and per address, at the gateway and for costly endpoints separately.
- Maximum page sizes, upload sizes, request body sizes and query depth (for GraphQL, also query complexity and a ban on unlimited batching).
- Timeouts on every outgoing call and every database query.
- Spending caps on anything that costs per call, such as SMS, email or AI model APIs: attackers will happily make you send 100,000 text messages.
- For business flows bots love (sign-up, checkout, gift cards, ticket sales): device and behaviour checks, per-account limits and alerts on unusual volume.
5. Do not fetch whatever you are told (API7)
Features such as "import from URL", webhooks and link previews make your server fetch an address the user supplies. Without checks, an attacker points it at internal services, or at the cloud metadata service (169.254.169.254) that can hand out the server's cloud credentials.
- Allow-list the schemes (
httpsonly) and, where you can, the destination hosts. - Resolve the name, then check the address is not private, loopback, link-local or your own network, and connect to that checked address (so a second DNS answer cannot swap it).
- Do not follow redirects, or re-check each one.
- Fetch from an isolated worker with no access to internal networks, and on AWS require IMDSv2 for the metadata service.
6. Know every API you run (API8, API9 and API10)
- Keep an inventory: every API, version, environment, owner and the data it handles, ideally generated from your OpenAPI files and gateway configuration.
- Retire old versions on a published schedule.
/v1left running without the fixes made in/v2is a favourite way in. - Keep test and staging APIs off the internet, and never load them with real personal information.
- Tighten the defaults: TLS only, CORS limited to your own origins, generic error messages, no debug or metrics endpoints exposed.
- Treat third-party API responses as untrusted input: validate them, limit their size, set timeouts and never follow their redirects blindly.
7. Test it like an attacker
- Automated authorization tests with two users and two tenants for every endpoint that takes an ID.
- A dynamic scanner such as OWASP ZAP run against your OpenAPI definition in CI.
- Fuzzing of request bodies for unexpected fields, types and sizes.
- Logging and alerts on authorization failures: one user hitting hundreds of
404s on sequential IDs is an attack in progress.
API review checklist
- Does every endpoint that takes an ID check the caller may use that record?
- Are tokens verified with a pinned algorithm, expiry, issuer and audience?
- Are request and response fields defined by a schema, with unknown fields refused?
- Are there rate limits, size limits and timeouts, and spending caps on paid services?
- Does any feature fetch a user-supplied address, and is it protected against SSRF?
- Is the API in the inventory, with an owner and a retirement date for old versions?
▲ Why it matters in Canada
Broken authorization in an API is one of the most common ways personal information leaks in bulk, one record at a time. Under PIPEDA, a breach of security safeguards that creates a real risk of significant harm must be reported to the Office of the Privacy Commissioner of Canada and to the people affected, and Quebec's Law 25 adds its own reporting duty and penalties. An attacker who enumerates your customer records through an API is a reportable breach, even if no server was "hacked".
Keep learning
Next: model the threats to a new feature before you build it, and secure the pipeline that ships it.
