REST API Security · Lesson 18 of 30
REST API Security Best Practices and Rate Limiting
APIs are now the main target of web attacks, because they expose data and actions directly. Most real breaches aren't clever crypto attacks – they're missing authorisation checks, unlimited requests and over-exposed data. The OWASP API Security Top 10 lists the most common problems; this lesson walks through them and implements two of the most important defences.
In this lesson
- The OWASP API Security Top 10
- Broken Object Level Authorisation – the number one risk
- Rate limiting with 429 – shown live
- A security checklist
OWASP API Security Top 10 (2023)
| Risk | In plain words |
|---|---|
| API1 Broken Object Level Authorisation | change the id in /orders/1001 to 1002 and see someone else's order |
| API2 Broken Authentication | weak login, tokens that never expire, unverified JWTs |
| API3 Broken Object Property Level Authorisation | responses leak fields (password hashes) or accept fields they shouldn't (role) |
| API4 Unrestricted Resource Consumption | no rate limits, unlimited page sizes or uploads |
| API5 Broken Function Level Authorisation | regular users can call admin endpoints |
| API6 Unrestricted Access to Sensitive Business Flows | bots buying all the tickets, mass sign-ups |
| API7 Server-Side Request Forgery | the API fetches a URL the attacker supplies – including internal ones |
| API8 Security Misconfiguration | verbose errors, open CORS, missing TLS, default credentials |
| API9 Improper Inventory Management | forgotten old versions and test endpoints still online |
| API10 Unsafe Consumption of APIs | trusting data from third-party APIs without validation |
BOLA: check ownership on every object
// server.js
import express from 'express';
import rateLimit from 'express-rate-limit';
const app = express();
const invoices = [
{ id: 'inv_1001', customerId: 'c_asha', amount: 12000, cardLast4: '4242' },
{ id: 'inv_1002', customerId: 'c_ravi', amount: 8500, cardLast4: '1881' },
];
// pretend authentication already happened: the token belongs to Asha
app.use((req, res, next) => { req.user = { customerId: 'c_asha' }; next(); });
// ✗ vulnerable: any logged-in user can read any invoice by guessing ids
app.get('/api/v0/invoices/:id', (req, res) => {
const inv = invoices.find((i) => i.id === req.params.id);
return inv ? res.json(inv) : res.status(404).json({ error: 'Not found' });
});
// ✓ fixed: scope every lookup to the caller, and return only safe fields
const toPublic = ({ id, amount }) => ({ id, amount });
app.get('/api/v1/invoices/:id', (req, res) => {
const inv = invoices.find((i) => i.id === req.params.id && i.customerId === req.user.customerId);
return inv ? res.json(toPublic(inv)) : res.status(404).json({ error: 'Not found' });
});
// rate limit the login endpoint: 3 attempts per window per client
const loginLimiter = rateLimit({ windowMs: 60_000, limit: 3, standardHeaders: 'draft-8', legacyHeaders: false,
message: { error: 'Too many login attempts. Try again in a minute.' } });
app.post('/api/login', loginLimiter, (req, res) => res.status(401).json({ error: 'Invalid credentials' }));
app.listen(process.env.PORT ?? 3000);
$ curl http://localhost:3000/api/v0/invoices/inv_1002
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"id": "inv_1002",
"customerId": "c_ravi",
"amount": 8500,
"cardLast4": "1881"
}
$ curl http://localhost:3000/api/v1/invoices/inv_1002
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{
"error": "Not found"
}
$ curl http://localhost:3000/api/v1/invoices/inv_1001
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"id": "inv_1001",
"amount": 12000
}
$ curl -X POST http://localhost:3000/api/login
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
{
"error": "Invalid credentials"
}
$ curl -X POST http://localhost:3000/api/login
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
{
"error": "Invalid credentials"
}
$ curl -X POST http://localhost:3000/api/login
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
{
"error": "Invalid credentials"
}
$ curl -X POST http://localhost:3000/api/login
HTTP/1.1 429 Too Many Requests
Retry-After: 60
Content-Type: application/json; charset=utf-8
{
"error": "Too many login attempts. Try again in a minute."
}- The v0 endpoint handed Asha Ravi's invoice, card digits included – a textbook BOLA (also called IDOR) and API3 data over-exposure.
- v1 scopes the query by the caller (
customerIdfrom the token, never from the request) and returns 404 for other people's invoices, plus only safe fields. - The fourth login attempt got 429 Too Many Requests with
Retry-After. Every response also carried the standardRateLimitandRateLimit-Policyheaders (left out of the panel) telling clients how many requests remain. Rate-limit logins, password resets, OTPs and expensive searches especially. - Random, non-sequential ids make guessing harder, but they're not a substitute for the ownership check.
A security checklist
- Transport: HTTPS only, HSTS, modern TLS.
- Identity: proven auth (OAuth/OIDC or well-built tokens), short-lived credentials, MFA for admins.
- Authorisation: on every request – function level (role) and object level (ownership).
- Input: validate with schemas, allow-list fields, cap sizes and page lengths; parameterised queries.
- Output: return only what the client needs; generic error messages; no stack traces.
- Abuse: rate limits per user/IP/key, bot protection for sensitive flows, timeouts on outbound calls.
- Operations: secrets in a vault, dependency updates, an inventory of every API version, logging and alerting on auth failures.
In production, rate limiting usually lives in an API gateway (Kong, AWS API Gateway, Azure APIM, Cloudflare) or uses a shared store like Redis, so limits hold across many server instances.
Practice
Try it yourself
An endpoint
POST /api/fetch-preview {"url": "…"}downloads a page to build a link preview. Which OWASP risk is this, and how do you defend?Show answer
Server-Side Request Forgery (API7): an attacker can make your server call internal addresses such as
http://169.254.169.254/(cloud metadata) orhttp://localhost:6379. Allow only http/https, resolve the host and block private and link-local IP ranges, disable redirects or re-check them, set timeouts and size limits, and run the fetcher with minimal network access.
Quick check
What is BOLA?
Accessing other users' objects by changing an id, because the API doesn't check ownership.
Which status code and header signal a rate limit?
429 Too Many Requests with Retry-After (and RateLimit headers).
Where should the customer id for a lookup come from?
The authenticated token – never the request body or query.
Summary
- Most API breaches are authorisation and resource-limit failures – OWASP API Top 10.
- Check ownership on every object; return only safe fields.
- Rate-limit with 429 and Retry-After, ideally at the gateway; follow the checklist.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.