API Security
APIs expose application logic and data directly: the client is untrusted and every parameter is attacker-controlled, so there is no front end to hide behind. The dominant failure class is broken authorization — object-level (BOLA/IDOR) and function-level (BFLA) — not injection, and automated attackers enumerate IDs and endpoints at scale. This lesson goes deep on the OWASP API Security Top 10 2023: object- and function-level authorization, broken authentication and JWT pitfalls, broken object property level authorization (mass assignment + excessive data exposure), unrestricted resource consumption, SSRF, strict schema validation, service-to-service trust (gateways, mTLS, token scoping, key management), GraphQL-specific risks, REST vs GraphQL trade-offs, improper inventory management, and business-flow abuse — all anchored to one invariant: the server must independently re-derive who is calling, what object, and what action on every request.
Legal & ethical use
This lesson demonstrates offensive techniques for educational purposes and authorized security testing only. Using them against systems you do not own or lack explicit written permission to test is illegal under computer-misuse laws worldwide, including Turkey’s Penal Code (Law No. 5237, arts. 243-245). The authors and PrimeThreat accept no liability for any misuse of or damage arising from this material.
The fifteen building blocks of API security
From why APIs are their own discipline through every OWASP API Security Top 10 2023 category to a defensive checklist — each grounded in real OWASP API codes, technique IDs, CWEs, and RFC/NIST/ISO references.
Why API security is its own discipline (scope & framing)
Key points
- APIs expose application logic and data directly, removing the implicit shielding a server-rendered UI provided. The client is untrusted and every parameter is attacker-controlled — there is no "front end" to hide behind.
- This lesson extends the OWASP API Security Top 10 (2023) already summarized on /owasp, going deep on authorization, authentication, resource consumption, SSRF, input typing, service-to-service trust, and GraphQL.
- The dominant API failure class is BROKEN AUTHORIZATION (object- and function-level), not injection. Automated attackers enumerate IDs and endpoints, so server-side checks on every request are the core defense.
- Machine-to-machine traffic (microservices, mobile back-ends, partner integrations) means identity and least privilege must be carried in tokens and verified at each hop, not assumed from network position — this is zero trust.
- Frame the whole lesson around one invariant: the server must independently re-derive "who is calling, what object, what action" on every request — never trust client-supplied identity, role, or object ownership.
References
API1:2023 — Broken Object Level Authorization (BOLA / IDOR)
Key points
- BOLA: the API exposes an object identifier (e.g. /accounts/{id}) and fails to verify the caller is authorized for THAT specific object, letting an attacker swap the id to reach another tenant's data.
- The root weakness is authorization bypass through a user-controlled key — the object reference is trusted from the request instead of being bound to the authenticated subject server-side.
- Correct fix: on every request, look up the object, then check ownership/tenancy against the authenticated principal (from the validated token), denying by default; never rely on the id being unguessable.
- Using random UUIDs instead of sequential ids raises the bar but is NOT an authorization control — it is security-through-obscurity and BOLA still applies.
- Enforce centrally (a policy layer / middleware) so the check cannot be forgotten on a new endpoint; test by replaying requests with another user's session against the same object id.
References
API5:2023 — Broken Function Level Authorization (BFLA)
Key points
- BFLA: the caller invokes a function/endpoint they should not be allowed to (e.g. a normal user calling an admin-only DELETE, or a different HTTP method/route) because role-to-function checks are missing or client-side.
- Distinct from BOLA: BOLA is "which object", BFLA is "which action/operation". Attackers probe by changing the verb (GET→PUT/DELETE), guessing /admin/ paths, or calling undocumented endpoints.
- Fix: deny-by-default function authorization derived from the validated token's role/scope on the server; the gateway or framework should reject unauthorized method+route combinations before business logic runs.
- Administrative and privileged functions need explicit allowlists of who may call them; hiding the admin UI does nothing because the endpoint is still reachable directly.
- Test by enumerating every method on every route as a low-privilege principal and as an anonymous principal.
References
Server-side authorization as a non-negotiable invariant
Key points
- Authorization is a server-side decision made fresh on EVERY request from server-trusted identity (validated token claims), never from hidden form fields, headers the client can set, or client-side role flags.
- Prefer a centralized policy decision point (PDP) — e.g. attribute-based access control evaluated by a policy engine — so authorization logic is consistent and auditable across services rather than copy-pasted per endpoint.
- Combine object-level (BOLA) and function-level (BFLA) checks: verify both that the action is allowed for the role AND that the specific object belongs to / is permitted for the subject.
- In microservices, propagate the original caller identity (not just the service identity) so downstream services can re-authorize; a service-to-service mTLS identity is necessary but not sufficient.
- Fail closed: if the policy engine is unreachable or a claim is missing, deny.
References
API2:2023 — Broken Authentication
Key points
- Covers weak or absent authentication on endpoints, accepting unsigned or improperly validated tokens, missing brute-force / credential-stuffing protection, and exposed credential or token-issuance flows.
- JWT pitfalls to teach explicitly: accepting alg:none, confusing HMAC vs RSA keys (algorithm confusion), missing signature verification, and not validating iss, aud, exp, and nbf claims — follow the JWT best current practices.
- Validate the token audience (aud) and issuer (iss): a token minted for service A must be rejected by service B (this prevents confused-deputy token replay across services).
- Protect authentication endpoints: rate limit and lock out on repeated failures to blunt brute force, credential stuffing, and password spraying; prefer phishing-resistant MFA and short-lived access tokens with rotating refresh tokens.
- Never hard-code or ship secrets / API keys in mobile or SPA bundles; treat any client-embedded secret as public.
References
API3:2023 — Broken Object Property Level Authorization (mass assignment + excessive data exposure)
Key points
- API3:2023 merges two 2019 categories: Excessive Data Exposure (returning more object properties than the caller should see) and Mass Assignment (letting the caller write properties they should not).
- Excessive data exposure: returning full DB objects and relying on the client/UI to hide fields leaks sensitive properties (PII, internal flags). Shape responses with explicit output DTOs/serializers, never blanket object-to-JSON.
- Mass assignment: binding the entire request body to a model lets an attacker set privileged fields (e.g. role=admin, isVerified=true, balance) that were never meant to be client-writable.
- Fix mass assignment with an allowlist of bindable properties per operation (explicit input DTOs), and validate property-level authorization — who may read/write each field — not just object-level access.
- Test by adding unexpected fields to write requests and by inspecting responses for properties the UI never displays.
References
API4:2023 — Unrestricted Resource Consumption & rate limiting
Key points
- Without limits, a single client can exhaust CPU, memory, bandwidth, DB connections, or third-party quota (and money), causing application-level denial of service or runaway billing.
- Enforce rate limiting and quotas per client/identity/IP, and cap request body size, pagination page size, array lengths, file upload size, query execution time, and concurrent connections.
- Return HTTP 429 Too Many Requests with a Retry-After header when throttling so well-behaved clients back off.
- Watch resource-amplifying features specifically: endpoints that send SMS/email, trigger expensive computation, or fan out to other APIs need stricter, business-aware limits.
- This is also an application-layer DoS vector — rate limits, timeouts, and circuit breakers are both reliability and security controls.
References
API7:2023 — Server-Side Request Forgery (SSRF)
Key points
- SSRF: the API takes a user-supplied URL/host (webhooks, link preview, image fetch, PDF render, import-from-URL) and the server makes the request, letting an attacker pivot to internal services or the cloud metadata endpoint.
- The highest-impact target is the cloud instance metadata service (e.g. 169.254.169.254) to steal temporary IAM credentials — enforce IMDSv2 / metadata hardening as defense in depth.
- Defenses: allowlist destinations (scheme + host), resolve and validate the IP against blocked ranges AFTER DNS resolution, block redirects to disallowed hosts, and deny private / link-local / loopback ranges.
- Beware DNS rebinding and TOCTOU: validate then connect to the SAME resolved address; do not re-resolve. Disable unneeded URL schemes (file:, gopher:, ftp:).
- Egress-filter the service network so even a successful SSRF cannot reach sensitive internal endpoints; log outbound requests for detection.
References
Schema validation & strict input typing (positive security model)
Key points
- Validate every request against a strict schema (OpenAPI / JSON Schema for REST) — enforce types, formats, ranges, required fields, and enums, and reject unknown / additional properties (which also blunts mass assignment).
- Use a POSITIVE security model (an allowlist of what is valid) rather than trying to blacklist bad input; validate at the edge (gateway) AND in the service.
- Enforce Content-Type and parse strictly; reject mismatched or ambiguous content types to avoid parser-confusion and type-juggling bugs.
- Validate output too where it matters (e.g. the response conforms to the contract) so accidental over-exposure is caught.
- Schema-as-contract enables automated security testing (fuzzing against the spec) and keeps documentation, validation, and gateway policy in sync.
References
Service-to-service trust: gateways, mTLS, token scoping, key management
Key points
- An API gateway centralizes authentication, schema validation, rate limiting, and TLS termination — but business authorization (BOLA/BFLA) must still be enforced in the service; a gateway alone is not sufficient.
- Use mutual TLS (mTLS) for service-to-service authentication so each side proves identity with a certificate; certificate-bound access tokens prevent a stolen bearer token from being replayed by another client.
- Token scoping = least privilege for tokens: request only the OAuth scopes needed, restrict the audience (aud) to the target resource, and down-scope tokens when calling downstream services (token exchange) so a leaked token has minimal blast radius.
- Audience restriction / resource indicators stop the confused-deputy problem: a token issued for service A cannot be replayed against service B.
- Key/secret management: rotate keys, scope API keys narrowly, store secrets in a managed vault/KMS (never in code or env committed to git), and follow recognized key-management lifecycle guidance. Consider sender-constrained tokens (DPoP / mTLS) over plain bearer tokens.
References
GraphQL-specific risks
Key points
- Introspection exposes the full schema (types, fields, mutations); disable or restrict introspection in production and turn off verbose field-suggestion error messages that leak schema names.
- Query depth and complexity attacks: deeply nested or recursive queries (e.g. circular relations) can explode into a resource-exhaustion DoS — enforce maximum query depth, complexity/cost limits, and timeouts.
- Batching and aliasing can bypass naive rate limiting (many operations in one request) and amplify brute force — apply cost-based limits and per-operation accounting, not just per-request counting.
- Authorization must be enforced per-field / per-resolver: a single GraphQL endpoint multiplexes many operations, so BOLA/BFLA checks live at the resolver level, never at the transport.
- Disable or guard mutations and dangerous fields; treat a persisted-queries allowlist as a hardening option for trusted clients.
References
REST vs GraphQL (security trade-offs)
Key points
- REST: many endpoints with fixed shapes — authorization and rate limiting map naturally to URL + method, but over-fetching encourages excessive data exposure if responses are not shaped per consumer.
- GraphQL: one flexible endpoint — great for clients, but it moves the attack surface into query complexity and per-field authorization, and breaks endpoint-based rate limiting and WAF rules.
- Common to both: server-side object- and function-level authorization, strict input validation, resource limits, and avoiding excessive data exposure — the principles are identical, the enforcement points differ.
- Choose limits to match the paradigm: per-route quotas for REST; query-cost / depth limits and resolver-level authz for GraphQL.
- Document and inventory either way — a flexible GraphQL schema still needs the same change control and exposure review as REST endpoints.
References
API9:2023 — Improper Inventory Management (shadow & zombie APIs)
Key points
- You cannot secure what you do not know exists: undocumented (shadow) APIs and deprecated-but-still-live (zombie) APIs are prime targets because they skip current controls.
- Old API versions (e.g. /v1 left running after /v2 ships) often lack the latest authentication, validation, and rate limiting — retire them on a schedule and block them at the gateway.
- Maintain an authoritative, automatically updated inventory of every host, environment (especially non-production exposed to the internet), endpoint, version, and data classification.
- Track who/what consumes each API and what data flows through it so exposure and decommissioning decisions are data-driven.
- Non-production and debug endpoints exposed publicly are a recurring breach source; treat staging/test the same as prod for exposure.
References
API6:2023 & API10:2023 — business-flow abuse and unsafe consumption of third-party APIs
Key points
- API6:2023 Unrestricted Access to Sensitive Business Flows: automation abuses a legitimate flow at scale (bulk purchase / scalping, mass account creation, comment spam) — defend with bot detection, device fingerprinting, throttling, and human-in-the-loop, not just per-request validation.
- API10:2023 Unsafe Consumption of APIs: developers over-trust data from third-party / upstream APIs; validate and sanitize responses from integrated services exactly as you would direct user input.
- Treat upstream API failures defensively: timeouts, response-size limits, and not blindly following redirects from a third-party service (which can itself be an SSRF vector).
- Apply schema validation to inbound third-party data and enforce least privilege on the credentials you hold for them.
- These two rounding out the Top 10 reinforce the lesson's thesis: trust nothing — not the client, not the network, not even partner APIs.
References
Defensive checklist & testing
Key points
- Authorization: deny-by-default, centralized policy, re-check object ownership AND function/role on every request; automated test that replays each endpoint as anonymous / other-tenant / low-privilege.
- Authentication: short-lived signed tokens with iss/aud/exp validation, strong JWT algorithm handling, MFA, and brute-force protection on auth endpoints.
- Inputs/outputs: strict schema validation rejecting unknown fields (kills mass assignment), output DTOs (kills excessive data exposure), and size / pagination caps.
- Resource control: per-identity rate limits, quotas, timeouts, 429 + Retry-After, and SSRF egress allowlisting plus metadata-service hardening.
- Operate: maintain an API inventory, retire old versions, log and monitor authorization failures and outbound requests, and align to a recognized control framework (ISO/IEC 27001:2022 secure-development controls).