読み物Application Security

Level: Intermediate

API Security: Protecting Tokens, Secrets, and Sensitive Data

Protect APIs from the risks in the OWASP API Security Top 10: object-level checks, response shaping, rate limits, token validation, and keeping secrets out of code.

Edeeson Opina9 min read

An Intermediate lesson card: lesson 10 of the Security & Privacy series, API Security: Protecting Tokens, Secrets, and Sensitive Data, with the Miso fox excited.

What you’ll learn

  • Map API bugs to the OWASP API Security Top 10:2023
  • Return only allowlisted fields and accept only allowlisted input
  • Validate JSON Web Tokens correctly, or choose opaque tokens
  • Keep secrets out of code, logs, and client bundles
  • Add rate limits and size limits to expensive endpoints
On this page
  1. Before you start
  2. The OWASP API Security Top 10
  3. Shape responses with allowlists
  4. Validate input with schemas
  5. Limit resource consumption
  6. Tokens: opaque or JWT
  7. Keep secrets out of code
  8. Verify webhooks and third-party data
  9. Keep an inventory
  10. Common mistakes and troubleshooting
  11. Practical exercise: harden one API
  12. Key takeaways
  13. References
  14. What's next

Modern applications are mostly APIs: a front end, a mobile app, partner integrations, and internal services all talking to endpoints that return JSON. APIs expose data and actions directly, without a user interface to hide anything, and they're easy to call at scale. This lesson maps the OWASP API Security Top 10:2023 to concrete code, then covers the practical work of shaping responses, validating input, limiting resource use, validating tokens, and keeping secrets where they belong.

Before you start

You should have read Secure Authentication, Authorization, and Session Management, because authorization is at the heart of API security. Examples use TypeScript with Express-style handlers, Prisma, and the Zod validation library.

The OWASP API Security Top 10

OWASP publishes a separate Top 10 for APIs; the current edition is from 2023. Like the main Top 10, it's an awareness list, not a standard:

  1. API1 Broken Object Level Authorization (BOLA): an endpoint returns or changes an object without checking that the caller may access it.
  2. API2 Broken Authentication: weak token handling, missing rate limits on credential endpoints, or tokens accepted without proper validation.
  3. API3 Broken Object Property Level Authorization: responses expose properties the caller shouldn't see, or requests can set properties they shouldn't (mass assignment).
  4. API4 Unrestricted Resource Consumption: no limits on request rate, payload size, page size, or expensive operations.
  5. API5 Broken Function Level Authorization: regular users can call administrative functions.
  6. API6 Unrestricted Access to Sensitive Business Flows: automated abuse of legitimate flows, such as bulk-buying limited stock or mass account creation.
  7. API7 Server Side Request Forgery: the API fetches a URL supplied by the caller without validation.
  8. API8 Security Misconfiguration: permissive CORS, verbose errors, missing TLS, unnecessary HTTP methods.
  9. API9 Improper Inventory Management: old API versions, debug endpoints, and undocumented hosts left running.
  10. API10 Unsafe Consumption of APIs: trusting data from third-party APIs more than user input.

Lesson 9 covered object- and function-level authorization (API1 and API5). Lesson 12 covers SSRF (API7). This lesson focuses on the rest.

Shape responses with allowlists

API3 is common because it's so easy to write res.json(user). The database row contains everything: email, password hash, internal flags, the date of the last failed sign-in. The front end may show only the name, but every field is visible in the network response.

insecure-user-response.tsTypeScript
// INSECURE TEACHING EXAMPLE: returns every column, including the password hash.
app.get("/api/users/:id", requireSession, async (req, res) => {
  res.json(await db.user.findUnique({ where: { id: req.params.id } }));
});

Select only what the caller needs, and define response shapes explicitly:

user-response.tsTypeScript
const publicUser = { id: true, displayName: true, avatarUrl: true } as const;

app.get("/api/users/:id", requireSession, async (req, res) => {
  const user = await db.user.findUnique({ where: { id: req.params.id }, select: publicUser });
  if (!user) return res.sendStatus(404);
  res.json(user);
});

Selecting fields in the query is better than deleting fields afterwards, because new sensitive columns added later won't leak by default.

Validate input with schemas

The same principle applies in the other direction. Parse every request body against a schema that lists the allowed fields, their types, and their limits. Unknown fields are rejected, which prevents mass assignment:

update-profile.tsTypeScript
import { z } from "zod";

const UpdateProfile = z
  .object({
    displayName: z.string().trim().min(1).max(80),
    bio: z.string().max(500).optional(),
  })
  .strict(); // rejects extra keys such as "role" or "isAdmin"

app.patch("/api/me", requireSession, async (req, res) => {
  const parsed = UpdateProfile.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: "Invalid profile data." });
  const user = await db.user.update({ where: { id: req.session.userId }, data: parsed.data, select: publicUser });
  res.json(user);
});

Validation is not a replacement for parameterized queries or output encoding; it's an extra layer that rejects malformed input early and documents what the endpoint accepts.

Limit resource consumption

Every API endpoint costs something: CPU, memory, database time, emails, SMS fees, third-party API quotas. Without limits, a single client can exhaust them, by accident or on purpose (API4). Set limits at several levels:

  • Request body size: for example, express.json({ limit: "100kb" }). Larger uploads go to dedicated endpoints with their own limits.
  • Pagination: a maximum page size enforced on the server, whatever the client asks for.
  • Rate limits: per user and per IP address, stricter on expensive or sensitive endpoints such as sign-in, password reset, search, and anything that sends messages.
  • Timeouts: on database queries and outgoing HTTP calls.
limits.tsTypeScript
const PageQuery = z.object({
  cursor: z.string().max(64).optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20),
});

app.get("/api/orders", requireSession, async (req, res) => {
  const { cursor, limit } = PageQuery.parse(req.query);
  const orders = await db.order.findMany({
    where: { accountId: req.session.accountId },
    take: limit + 1,
    ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
    orderBy: { id: "asc" },
  });
  res.json({ items: orders.slice(0, limit), nextCursor: orders.length > limit ? orders[limit - 1]!.id : null });
});

When a limit is hit, return 429 Too Many Requests with a Retry-After header. For business-flow abuse (API6), such as scalping or fake sign-ups, rate limits alone aren't enough: add per-account quotas, verification steps, and monitoring for unusual patterns.

Tokens: opaque or JWT

APIs used by non-browser clients usually authenticate with a bearer token in the Authorization header. There are two broad kinds:

  • Opaque tokens are random strings that the API looks up in a database or asks the authorization server about (token introspection). They're easy to revoke and reveal nothing if leaked.
  • JSON Web Tokens (JWTs) are signed, self-contained tokens carrying claims such as the user ID, audience, and expiry. They can be verified without a database lookup, which is useful across services, but they're hard to revoke before they expire.

If you accept JWTs, validate them properly with a maintained library, and check every claim that matters:

verify-token.tsTypeScript
import { createRemoteJWKSet, jwtVerify } from "jose";

const jwks = createRemoteJWKSet(new URL("https://auth.your-company.test/.well-known/jwks.json"));

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, jwks, {
    issuer: "https://auth.your-company.test/",
    audience: "orders-api",
    algorithms: ["RS256"], // never accept "none", and never let the token choose
    clockTolerance: 30,
  });
  return payload; // includes sub, scope, exp
}

Key rules for JWTs:

  • Pin the algorithm and reject none. Accepting whatever algorithm the token header names has led to signature bypasses.
  • Check issuer, audience, and expiry. A token issued for another service shouldn't work on yours.
  • Keep lifetimes short (minutes, not days) and use refresh tokens, stored securely, to get new ones.
  • Don't put secrets or personal data in the payload. A JWT is signed, not encrypted; anyone holding it can read it.
  • Don't store tokens in localStorage in browser apps; any XSS can read them. For browser front ends, prefer a server-side session in an HttpOnly cookie, or a backend-for-frontend that holds tokens on the server.

For delegated access between applications, use OAuth 2.0 with current best practice: the authorization code flow with PKCE, exact redirect URI matching, and no implicit flow. RFC 9700 (OAuth 2.0 Security Best Current Practice, 2025) collects these recommendations.

Keep secrets out of code

API keys, database passwords, signing keys, and webhook secrets are the keys to your systems. Most leaks are mundane: a key committed to Git, a key bundled into front-end JavaScript, a key printed in logs, a key pasted into a support ticket.

  • Never commit secrets. Load them from environment variables or a secrets manager at runtime, and keep .env files out of Git with .gitignore.
  • Scan for secrets in CI and in pre-commit hooks with tools such as Gitleaks or GitHub's secret scanning and push protection.
  • Never expose server secrets to the browser. In Next.js, only variables prefixed NEXT_PUBLIC_ are bundled into client code; anything with that prefix is public. A secret key in the browser is a public key.
  • Scope and rotate. Give each key the minimum permissions it needs, one key per service and environment, and rotate on a schedule and immediately after any suspected exposure.
  • Redact in logs. Never log Authorization headers, cookies, or request bodies of credential endpoints.
config.tsTypeScript
import { z } from "zod";

// Fail at startup, not at the first request, if a required secret is missing.
const Env = z.object({
  DATABASE_URL: z.string().url(),
  PAYMENT_API_KEY: z.string().min(20),
  WEBHOOK_SIGNING_SECRET: z.string().min(32),
});

export const env = Env.parse(process.env);

If a secret leaks, assume it's been used. Revoke it, issue a new one, check the provider's logs for misuse, and only then clean up the Git history.

Verify webhooks and third-party data

Webhooks are API calls *into* your system from a provider, and anyone can send a request to a public URL. Verify the provider's signature with a constant-time comparison before trusting the body:

webhook.tsTypeScript
import { createHmac, timingSafeEqual } from "node:crypto";

export function isValidSignature(rawBody: Buffer, signatureHex: string, secret: string): boolean {
  const expected = createHmac("sha256", secret).update(rawBody).digest();
  const received = Buffer.from(signatureHex, "hex");
  return received.length === expected.length && timingSafeEqual(received, expected);
}

Check the provider's documentation for the exact signing scheme, and also check timestamps to reject replays. More generally (API10), treat data from third-party APIs as untrusted input: validate it with schemas, set timeouts, and don't follow their redirects blindly.

Keep an inventory

API9 is about forgotten endpoints: a v1 API nobody maintains, a staging host with production data, a debug route left enabled. Keep a list of every API host, version, and environment, with an owner. Describe your APIs with OpenAPI so the list is accurate, and retire old versions on a published schedule.

Common mistakes and troubleshooting

  • Returning whole objects. Select fields explicitly.
  • Trusting client-side validation. Validate on the server with a schema.
  • No maximum page size. Clients can request a million rows.
  • Long-lived JWTs without revocation. Keep them short, or use opaque tokens.
  • Secrets in front-end bundles or Git. Scan for them, and keep them server-side.
  • Wildcard CORS with credentials. Allow specific origins only.

If a client receives 401 with a valid-looking JWT, decode its payload (without trusting it) and compare iss, aud, and exp with what your API expects; mismatched audiences and clock skew are the usual causes.

Practical exercise: harden one API

For an API you build or maintain, locally or in staging:

  1. List every endpoint with its method, the objects it touches, and who should call it.
  2. Add explicit select or response mapping to every endpoint that returns database objects.
  3. Add strict schema validation to every endpoint that accepts a body.
  4. Enforce a maximum page size and a body size limit, and add rate limits to sign-in and any endpoint that sends messages.
  5. Run a secret scanner over the repository history and fix anything it finds.

Key takeaways

  • Use the OWASP API Security Top 10:2023 to review APIs; BOLA (API1) is the most common serious issue.
  • Allowlist fields in responses and in accepted input; reject unknown keys.
  • Limit body size, page size, request rate, and time on every endpoint.
  • Validate JWTs strictly (algorithm, issuer, audience, expiry), keep them short-lived, and keep them out of localStorage.
  • Keep secrets out of code, bundles, and logs; scope them, rotate them, and revoke on exposure.

References

What's next

You've finished the Intermediate level. The Pro level starts before the code is written: Threat Modeling and Secure-by-Design Software Architecture shows how to find design flaws while they're still cheap to fix.

See every lesson in Security & Privacy: Building Secure Applications