OWASP API Security Top 10
The ten most common ways APIs get broken, according to OWASP's 2023 list.

2026 has been a year of security vulnerabilities. Most of the big ones were in runtimes and infrastructure, things we can only patch when a fix comes out. But a lot of what goes wrong lives in our own code, and there we can do something about it, as long as we know what to look for.
Security problems don't show up in the error log. An endpoint that leaks other
people's data returns 200 OK and looks perfectly healthy. That's what makes
security easy to forget, and it's also why it matters more than almost anything
else we build.
OWASP's list of the ten risks that break APIs most often. This post goes through all ten. For each one there's a short explanation, an endpoint with the problem, and the same endpoint fixed.
The setup
The examples use Express with TypeScript,
Zod for validation and Prisma-style db calls. The ideas
are the same in any framework.
import express from "express";
const app = express();
// Every example assumes this middleware has already checked the login token// and put the signed-in user on the request.type User = { id: string; role: "user" | "admin" };
declare global { namespace Express { interface Request { user?: User; } }}requireAuth is the middleware that sets req.user, or answers 401 when
there's no valid token. How to write it properly is risk number 2.
API1: Broken Object Level Authorization
We're usually careful to check that the token is valid. What we often forget is the next question: is this user asking for their own order?
A valid token only proves who the caller is. It says nothing about which orders
they're allowed to see. So if /orders/123 only checks the token, a signed-in
user can change the number to 124 and read someone else's order.
This is the most common API bug there is, and it's at the top of the list for a reason.
// ❌ Any signed-in user can read any orderapp.get("/orders/:id", requireAuth, async (req, res) => { const order = await db.order.findUnique({ where: { id: req.params.id }, }); if (!order) return res.sendStatus(404); res.json(order);});The fix is to make ownership part of the query itself, so there is no way to fetch the row without the check:
// ✅ Only finds the order if it belongs to the callerapp.get("/orders/:id", requireAuth, async (req, res) => { const order = await db.order.findFirst({ where: { id: req.params.id, userId: req.user!.id }, }); if (!order) return res.sendStatus(404); res.json(order);});Answer 404, not 403, when the order belongs to someone else. A 403 tells
the attacker the id exists.
API2: Broken Authentication
Most APIs use a JWT (JSON Web Token). When a user logs in, the server gives them a token, and on every request after that the user sends the token back. The server reads it and treats the caller as "this logged-in user".
(New to JWTs? JWT Explained covers what's inside a token and how the signature works.)
What makes a JWT safe is its signature. The server signs each token with a secret key, so when a token comes back, the server has to check that signature first. If it skips that step, anyone can write their own token with any user's name in it and log in as that person.
The vulnerable version
import { decodeJwt } from "jose";
app.get("/vuln/me", (req, res) => { const token = req.headers.authorization?.slice("Bearer ".length) ?? "";
// ❌ decodeJwt() only reads the token. It never checks the signature, // so a forged token is trusted. const payload = decodeJwt(token);
res.json({ loggedInAs: payload.sub, verified: false });});decodeJwt() throws away the only protection a JWT has. The code reads sub
(the subject, meaning the user id) out of the token and believes it. A token
made by someone who doesn't even know the secret key is accepted.
Why skipping the signature is so dangerous
decodeJwt() never verifies the signature. There's no option to turn
checking on; it only reads what's inside the token. To check the signature you
have to call jwtVerify() instead.
decodeJwt(token); // ❌ reads the token, never checks the signatureawait jwtVerify(token, JWT_SECRET, { algorithms: ["HS256"] }); // ✅ checks, then readsWhy is that so bad? A JWT is not encrypted. It's three pieces
of base64 text joined by dots: a header, the data (the "payload") and the
signature. Here's a real one, for the user alice:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIsImlhdCI6MTc2MzUzOTIwMCwiZXhwIjoxNzYzNTQwMTAwfQ.346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bgSplit at the dots and decode each piece, and you can read it without any key:
// 1. Header: which algorithm signed it{ "alg": "HS256", "typ": "JWT" }
// 2. Payload: who the token is for, and when it expires{ "sub": "alice", "iat": 1763539200, "exp": 1763540100 }
// 3. Signature: 346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bg// Made from the header + payload + the server's secret key.// This is the only part an attacker can't make themselves.Because the payload is just base64, anyone can change it and encode it again:
// What an attacker does. No secret key needed.const [header, , signature] = aliceToken.split(".");
const fakePayload = Buffer.from( JSON.stringify({ sub: "admin", role: "admin", exp: 9999999999 }),).toString("base64url");
const forged = `${header}.${fakePayload}.${signature}`;The forged token looks just as real as the first one. Only the middle part changed:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiIsImV4cCI6OTk5OTk5OTk5OX0.346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bgThe old signature no longer matches the new payload. The signature is the only thing that can catch that, so if nobody checks it, the forged token works. Skipping the check means:
- Anyone can be anyone. The attacker puts any user id in
suband is logged in as that user, no password needed. - Anyone can be an admin. Any field in the token can be changed:
role: "admin",isPaid: true, a different company id. - Expiry stops meaning anything. The attacker writes their own
exp, so a token can be made to last forever. - Logging out doesn't help. Changing your password doesn't help either. The attacker never needed your token, only the shape of one.
- Nothing shows up in the logs. Every forged request looks like a normal,
successful login and returns
200.
The safe version
The fixed code checks the signature, pins the algorithm, and turns away tokens that have no expiry.
import { jwtVerify } from "jose";
// ✅ The secret comes from the environment, never from the codeconst JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);
app.get("/safe/me", async (req, res) => { const token = req.headers.authorization?.slice("Bearer ".length) ?? "";
try { const { payload } = await jwtVerify(token, JWT_SECRET, { // ✅ Verify the signature and pin the algorithm algorithms: ["HS256"], // ✅ Require an expiry and a subject requiredClaims: ["exp", "sub"], });
res.json({ loggedInAs: payload.sub, verified: true }); } catch (err) { logger.warn({ err }, "rejected token"); res.status(401).json({ error: "Invalid token" }); }});Each line here does a specific job:
jwtVerifyinstead ofdecodeJwt: the token is only read after the signature has been checked against our secret.algorithms: ["HS256"]: the token's header says which algorithm it was signed with, and an attacker can write anything there, includingalg: "none"(no signature at all). Pinning the algorithm means the server decides, not the token.- Requiring
exp: a token with no expiry works forever, so one stolen token is a permanent login. - The secret in an environment variable: if the secret is written in the code, anyone who sees the code (a leaked repo, an old commit, a former employee) can sign tokens that pass every check. At that point checking the signature means nothing.
When we create tokens, we give them a short life:
import { SignJWT } from "jose";
const token = await new SignJWT({}) .setProtectedHeader({ alg: "HS256" }) .setSubject(user.id) .setExpirationTime("15m") .sign(JWT_SECRET);Trying it with a forged token
To see the difference, make a token signed with the wrong secret, the way an attacker would without knowing ours:
// forge.tsimport { SignJWT } from "jose";
new SignJWT({ sub: "alice" }) .setProtectedHeader({ alg: "HS256" }) .setExpirationTime("1h") .sign(new TextEncoder().encode("attacker-guessed-secret")) .then(console.log);Then send it to both endpoints:
FORGED=$(npx tsx forge.ts)
curl -s localhost:3000/vuln/me -H "Authorization: Bearer $FORGED"# {"loggedInAs":"alice","verified":false} → HTTP 200, forged token accepted
curl -s localhost:3000/safe/me -H "Authorization: Bearer $FORGED"# {"error":"Invalid token"} → HTTP 401, forged token rejectedThe vulnerable endpoint answers 200 and says "you're logged in as alice". The
safe endpoint finds the signature doesn't match and answers 401.
The difference between the two is one function call. That one call is what stops anyone from logging in as anyone.
The login endpoint
The login endpoint needs care too: compare password hashes, give the same answer whether the email exists or not, and slow down repeated attempts.
import bcrypt from "bcrypt";import rateLimit from "express-rate-limit";
const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 5 });
app.post("/login", loginLimiter, async (req, res) => { const { email, password } = LoginBody.parse(req.body); const user = await db.user.findUnique({ where: { email } });
const ok = user && (await bcrypt.compare(password, user.passwordHash)); if (!ok) return res.status(401).json({ error: "Wrong email or password" });
res.json({ token: signToken(user) });});API3: Broken Object Property Level Authorization
API1 is about which objects you can reach. This one is about which fields of an object you can read or change. It has two halves:
- Excessive data exposure: the API sends back fields the caller shouldn't see, and trusts the frontend to hide them.
- Mass assignment: the API saves whatever fields the caller sends, including ones they shouldn't be able to set.
// ❌ Sends passwordHash, email, isAdmin… to anyone viewing a profileapp.get("/users/:id", requireAuth, async (req, res) => { const user = await db.user.findUnique({ where: { id: req.params.id } }); res.json(user);});
// ❌ { "role": "admin" } in the body makes you an adminapp.patch("/users/me", requireAuth, async (req, res) => { const user = await db.user.update({ where: { id: req.user!.id }, data: req.body, }); res.json(user);});The fix is to be explicit in both directions: a schema for what may come in, and a function for what goes out.
import { z } from "zod";
// Only these fields can be changed. .strict() rejects anything extra.const UpdateProfile = z .object({ name: z.string().min(1).max(80).optional(), bio: z.string().max(500).optional(), }) .strict();
// Only these fields are ever sent to other users.function toPublicUser(user: DbUser) { return { id: user.id, name: user.name, bio: user.bio };}
app.get("/users/:id", requireAuth, async (req, res) => { const user = await db.user.findUnique({ where: { id: req.params.id } }); if (!user) return res.sendStatus(404); res.json(toPublicUser(user));});
app.patch("/users/me", requireAuth, async (req, res) => { const result = UpdateProfile.safeParse(req.body); if (!result.success) return res.status(400).json(result.error.flatten());
const user = await db.user.update({ where: { id: req.user!.id }, data: result.data, }); res.json(toPublicUser(user));});Adding a new column to the database now doesn't quietly add it to the API. Someone has to put it in the list on purpose.
API4: Unrestricted Resource Consumption
Every request costs something: CPU, memory, database time, and sometimes real money when the endpoint sends an SMS or an email through a paid service. An API with no limits lets one caller use up all of it, either taking the service down or running up the bill.
// ❌ ?limit=10000000 loads the whole table into memoryapp.get("/products", async (req, res) => { const limit = Number(req.query.limit ?? 20); res.json(await db.product.findMany({ take: limit }));});
// ❌ Each call sends a paid SMS, as often as anyone likesapp.post("/verify-phone", requireAuth, async (req, res) => { await sms.send(req.body.phone, makeCode()); res.sendStatus(204);});// ✅ Cap the body size for every routeapp.use(express.json({ limit: "100kb" }));
// ✅ Cap the page size, whatever the caller asks forconst ListQuery = z.object({ limit: z.coerce.number().int().min(1).max(100).default(20), cursor: z.string().optional(),});
app.get("/products", async (req, res) => { const { limit, cursor } = ListQuery.parse(req.query); res.json( await db.product.findMany({ take: limit, ...(cursor && { cursor: { id: cursor }, skip: 1 }), }), );});
// ✅ Strict limits on anything that costs moneyconst smsLimiter = rateLimit({ windowMs: 60 * 60 * 1000, limit: 3, keyGenerator: (req) => req.user!.id, // per account, not just per IP});
app.post("/verify-phone", requireAuth, smsLimiter, async (req, res) => { const { phone } = z.object({ phone: z.string().regex(/^\+\d{8,15}$/) }).parse(req.body); await sms.send(phone, makeCode()); res.sendStatus(204);});Also set timeouts on database queries and outgoing requests, and limit file upload sizes. A request that never finishes holds on to resources too.
API5: Broken Function Level Authorization
API1 was about whose data you can reach. This one is about which actions you can take. Admin endpoints are often protected only by not being linked from the regular app, which protects nothing: the URLs are easy to guess.
// ❌ Logged in is enough to delete any userapp.delete("/admin/users/:id", requireAuth, async (req, res) => { await db.user.delete({ where: { id: req.params.id } }); res.sendStatus(204);});Put the role check in one middleware, and apply it to the whole admin section at once, so a new admin route can't be added without it:
function requireRole(role: User["role"]) { return (req: Request, res: Response, next: NextFunction) => { if (req.user?.role !== role) return res.sendStatus(403); next(); };}
// ✅ Every route on this router is admin-onlyconst admin = express.Router();admin.use(requireAuth, requireRole("admin"));
admin.delete("/users/:id", async (req, res) => { await db.user.delete({ where: { id: req.params.id } }); res.sendStatus(204);});
app.use("/admin", admin);Watch out for actions hidden behind the HTTP method too. If GET /users/:id is
fine for everyone, that says nothing about DELETE /users/:id or
PUT /users/:id. Check each one.
API6: Unrestricted Access to Sensitive Business Flows
This one usually isn't a bug in the code. The endpoint works exactly as written. The problem is what happens when a script calls it a thousand times a second: bots buying every concert ticket to resell them, creating thousands of accounts to farm a sign-up bonus, or spamming comments.
// ❌ A bot can buy all 500 tickets in one secondapp.post("/events/:id/tickets", requireAuth, async (req, res) => { const { quantity } = req.body; await db.ticket.createMany({ data: Array.from({ length: quantity }, () => ({ eventId: req.params.id, userId: req.user!.id, })), }); res.sendStatus(201);});Think about how the flow could hurt the business if automated, and add limits that match the real-world rules:
const MAX_TICKETS_PER_PERSON = 4;
const BuyTickets = z.object({ quantity: z.number().int().min(1).max(MAX_TICKETS_PER_PERSON), captchaToken: z.string(),});
app.post("/events/:id/tickets", requireAuth, async (req, res) => { const { quantity, captchaToken } = BuyTickets.parse(req.body);
// ✅ Make it expensive for scripts if (!(await verifyCaptcha(captchaToken))) return res.sendStatus(403);
// ✅ Enforce the per-person limit across all purchases, not just this one await db.$transaction(async (tx) => { const owned = await tx.ticket.count({ where: { eventId: req.params.id, userId: req.user!.id }, }); if (owned + quantity > MAX_TICKETS_PER_PERSON) { throw new HttpError(409, "Ticket limit reached"); } await tx.ticket.createMany({ data: Array.from({ length: quantity }, () => ({ eventId: req.params.id, userId: req.user!.id, })), }); });
res.sendStatus(201);});Other tools that help: requiring a verified phone or payment method before high-value actions, rate limits per account, and watching for patterns like many accounts from the same device or card.
API7: Server Side Request Forgery
Some features fetch a URL the user gave you: "import avatar from URL", link
previews, webhooks. If the server fetches whatever it's handed, an attacker can
make it request addresses only the server can reach, like the cloud metadata
service at 169.254.169.254 (which hands out credentials) or an internal admin
panel behind the firewall.
// ❌ url = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"app.post("/avatar/from-url", requireAuth, async (req, res) => { const image = await fetch(req.body.url); await saveAvatar(req.user!.id, await image.arrayBuffer()); res.sendStatus(204);});The safe version checks the URL and where it actually points:
import { lookup } from "node:dns/promises";import { BlockList } from "node:net";
const privateRanges = new BlockList();privateRanges.addSubnet("0.0.0.0", 8);privateRanges.addSubnet("10.0.0.0", 8);privateRanges.addSubnet("127.0.0.0", 8);privateRanges.addSubnet("169.254.0.0", 16); // cloud metadata lives hereprivateRanges.addSubnet("172.16.0.0", 12);privateRanges.addSubnet("192.168.0.0", 16);privateRanges.addAddress("::1", "ipv6");privateRanges.addSubnet("fc00::", 7, "ipv6");privateRanges.addSubnet("fe80::", 10, "ipv6");
async function assertPublicUrl(raw: string): Promise<URL> { const url = new URL(raw); // throws on garbage if (url.protocol !== "https:") throw new HttpError(400, "HTTPS only");
// A friendly-looking hostname can still point at 127.0.0.1 const addresses = await lookup(url.hostname, { all: true }); for (const { address, family } of addresses) { if (privateRanges.check(address, family === 6 ? "ipv6" : "ipv4")) { throw new HttpError(400, "That address isn't allowed"); } } return url;}
app.post("/avatar/from-url", requireAuth, async (req, res) => { const url = await assertPublicUrl(z.string().url().parse(req.body.url));
const image = await fetch(url, { redirect: "error", // a redirect could point somewhere private signal: AbortSignal.timeout(5_000), }); if (!image.headers.get("content-type")?.startsWith("image/")) { return res.status(400).json({ error: "Not an image" }); }
await saveAvatar(req.user!.id, await image.arrayBuffer()); res.sendStatus(204);});API8: Security Misconfiguration
None of the code here is wrong as such. It's settings: CORS that trusts every website, error messages that print stack traces, missing security headers, debug mode left on in production.
// ❌ origin: true copies back whatever Origin the browser sends, and// credentials: true lets any website make logged-in requests to your APIapp.use(cors({ origin: true, credentials: true }));
// ❌ Tells attackers your file paths, library versions and SQLapp.use((err: Error, req: Request, res: Response, next: NextFunction) => { res.status(500).json({ message: err.message, stack: err.stack });});import cors from "cors";import helmet from "helmet";
app.disable("x-powered-by"); // don't announce "Express"app.use(helmet()); // sensible security headers in one line
// ✅ Only your own frontendsapp.use( cors({ origin: ["https://example.com", "https://admin.example.com"], credentials: true, }),);
// ✅ Full details in your logs, a plain message for the callerapp.use((err: unknown, req: Request, res: Response, next: NextFunction) => { if (err instanceof HttpError) { return res.status(err.status).json({ error: err.message }); } if (err instanceof z.ZodError) { return res.status(400).json({ error: "Invalid request" }); } logger.error({ err, path: req.path }); res.status(500).json({ error: "Something went wrong" });});It also helps to read all configuration in one place and fail at startup if something is missing, rather than quietly running with a default:
const Env = z.object({ NODE_ENV: z.enum(["development", "test", "production"]), JWT_SECRET: z.string().min(32), DATABASE_URL: z.string().url(),});
export const env = Env.parse(process.env); // crashes on boot if anything's wrongAPI9: Improper Inventory Management
You can only protect endpoints you know about. Over time APIs collect old versions that nobody updated, debug routes, and test servers that point at the real database. Attackers go looking for exactly those.
A common story: /v2/users gets the API1 fix, but /v1/users is still running
for an old mobile app, and it doesn't have the fix.
// ❌ Debug tools that are "only for local", until someone deploys with// NODE_ENV unsetif (process.env.NODE_ENV !== "production") { app.use("/debug", debugRouter);}
// ❌ Old version still live, still missing every fix since 2021app.use("/v1", v1Router);app.use("/v2", v2Router);// ✅ Debug routes need an explicit opt-in, not a missing variableif (env.ENABLE_DEBUG_ROUTES === "true" && env.NODE_ENV === "development") { app.use("/debug", debugRouter);}
// ✅ Old versions announce when they go away, then actually go awayconst V1_SUNSET = new Date("2027-03-01T00:00:00Z");
app.use("/v1", (req, res, next) => { if (Date.now() >= V1_SUNSET.getTime()) { return res.status(410).json({ error: "v1 has been retired, use /v2" }); } res.setHeader("Deprecation", "true"); res.setHeader("Sunset", V1_SUNSET.toUTCString()); next();}, v1Router);
app.use("/v2", v2Router);Code alone doesn't solve this one. Keep an up-to-date list (an OpenAPI file generated from your code is ideal) of every host, version and endpoint, who owns it and what data it touches. Shared fixes, like the auth middleware, should live in code that every version uses, not be copied into each.
API10: Unsafe Consumption of APIs
We validate everything the user sends, then trust whatever comes back from a third-party API as if it were our own data. If that service is hacked, or just buggy, its responses go straight into our database and our pages.
// ❌ Trusts the shape, the size and the content of someone else's responseapp.post("/addresses/lookup", requireAuth, async (req, res) => { const response = await fetch( `http://geo.example-partner.com/lookup?q=${req.body.query}`, ); const data = await response.json();
await db.$executeRawUnsafe( `INSERT INTO addresses (user_id, line1) VALUES ('${req.user!.id}', '${data.line1}')`, ); res.json(data);});That code has five problems: plain HTTP, the query isn't encoded, no timeout, no check of what came back, and the response is pasted into SQL. Treat a third-party API exactly like user input:
const GeoResult = z.object({ line1: z.string().max(200), city: z.string().max(100), country: z.string().length(2),});
app.post("/addresses/lookup", requireAuth, async (req, res) => { const { query } = z.object({ query: z.string().min(1).max(200) }).parse(req.body);
const url = new URL("https://geo.example-partner.com/lookup"); // ✅ HTTPS url.searchParams.set("q", query); // ✅ encoded properly
const response = await fetch(url, { redirect: "error", // ✅ don't follow it somewhere else signal: AbortSignal.timeout(3_000), // ✅ don't wait forever }); if (!response.ok) return res.status(502).json({ error: "Lookup failed" });
// ✅ Check the response like any untrusted input const result = GeoResult.safeParse(await response.json()); if (!result.success) return res.status(502).json({ error: "Lookup failed" });
// ✅ Parameterized, never string-built SQL await db.address.create({ data: { userId: req.user!.id, ...result.data }, }); res.json(result.data);});The short version
- Object level authorization: put
userIdin the query, every time. - Authentication:
verify, neverdecode; pin the algorithm; short expiry; rate-limit login. - Property level authorization: a schema for what comes in, a function for what goes out.
- Resource consumption: cap body size, page size and anything that costs money.
- Function level authorization: role checks on the router, not on each route.
- Business flows: ask what a bot could do with this endpoint, and limit it.
- SSRF: HTTPS only, check where the hostname really points, no redirects.
- Misconfiguration: strict CORS,
helmet, no stack traces, validate env on startup. - Inventory: know every version and endpoint you run, and retire old ones.
- Third-party APIs: validate their responses as carefully as user input.
Most of these come down to one habit: never assume. Not that the caller owns the object, not that the body only has the fields you expect, and not that the other API sends back what its docs say.