How to design and operate secure APIs — covering authentication, authorisation, rate limiting, input validation, the OWASP API Security Top 10, and API gateway patterns.
How to design and operate secure APIs — covering authentication, authorisation, rate limiting, input validation, the OWASP API Security Top 10, and API gateway patterns.
APIs are the attack surface of modern applications. Broken authentication, missing authorisation checks, and lack of rate limiting allow attackers to enumerate data, bypass access controls, and abuse functionality at scale.
Attackers can enumerate user accounts, access other users' data via IDOR, bypass payment flows, scrape your entire database, or cause denial of service — all through your own API.
Every API endpoint is protected by authentication, authorisation at the object and field level, rate limiting, input validation, and monitoring. Abuse is detected and blocked before it causes significant damage.
Lesson outline
The OWASP API Security Top 10 (2023) documents the most critical API security risks. Unlike the web application Top 10, these are specific to API patterns.
| # | Vulnerability | What it means | Example |
|---|---|---|---|
| API1 | Broken Object Level Authorization (BOLA/IDOR) | API accepts user-controlled IDs without checking if caller owns that object | GET /invoices/1234 works for any user, not just the invoice owner |
| API2 | Broken Authentication | Weak tokens, no expiry, predictable secrets, missing MFA for sensitive ops | JWT signed with "secret", API keys in URLs, no refresh token rotation |
| API3 | Broken Object Property Level Authorization | API returns or accepts more fields than the caller should see/set | User updates their profile and can set role: "admin" because it is not filtered |
| API4 | Unrestricted Resource Consumption | No rate limiting, pagination limits, or payload size limits | Attacker downloads entire user database via paginated /users?page=N |
| API5 | Broken Function Level Authorization | Admin endpoints not properly restricted to admin roles | DELETE /admin/users/{id} returns 200 for regular users |
| API6 | Unrestricted Access to Sensitive Business Flows | Automation-accessible flows designed for human use only | Bot buys all concert tickets in milliseconds via the ticket purchase API |
| API7 | Server-Side Request Forgery (SSRF) | API fetches user-supplied URLs, allowing access to internal services | POST /fetch?url=http://169.254.169.254/metadata returns AWS instance metadata |
| API8 | Security Misconfiguration | Verbose error messages, debug endpoints, permissive CORS, missing security headers | Stack traces in 500 errors reveal DB schema; CORS allows * |
| API9 | Improper Inventory Management | Old API versions still running, shadow APIs, unauthenticated test endpoints | /v1/users still reachable after v2 launched, with weaker auth |
| API10 | Unsafe Consumption of APIs | Trusting data from third-party APIs without validation | Webhook from payment provider used to set order status without signature verification |
Rate limiting protects APIs from brute force, credential stuffing, scraping, and denial of service. Different endpoints need different limits.
| Endpoint Type | Recommended Limit | Why |
|---|---|---|
| Login / auth | 5 attempts / 15 min per IP + per username | Prevents credential stuffing and brute force |
| Password reset | 3 requests / hour per email | Prevents email flooding and token enumeration |
| Public read API | 1,000 req/min per API key | Prevents scraping, protects backend load |
| Authenticated write | 100 req/min per user | Prevents automated abuse of write operations |
| File upload | 10 uploads/hour per user + size limit | Prevents storage abuse and DoS via large payloads |
| Search / full-text | 30 req/min per user | Search is expensive — prevents DB overload |
| Webhook delivery | Exponential backoff, max 10 retries | Prevents retry storms from unreachable endpoints |
Rate limiting must be at the API gateway — not just the application
Application-level rate limiting (Express rate-limit middleware) is bypassed if an attacker sends requests directly to your service, skipping the gateway. Implement rate limiting at the API gateway (Kong, AWS API Gateway, Nginx) so it applies regardless of how requests arrive.
1# Kong API Gateway — rate limiting + key auth + request validation2# kong.yaml (declarative config)34services:5- name: invoices-api6url: http://invoices-service:30007routes:8- name: invoices-route9paths: [/api/v1/invoices]10methods: [GET, POST, PUT, DELETE]11plugins:12# Authentication13- name: jwt14config:JWT validation — verify signature, expiry, not-before15claims_to_verify: [exp, nbf]16key_claim_name: kid1718# Rate limiting per consumer (authenticated user)19- name: rate-limiting20config:21minute: 100 # 100 req/min per consumerRedis backend — rate limit state shared across all gateway instances22hour: 3000fault_tolerant: false — if Redis is down, reject requests (fail closed)23policy: redis # Use Redis for distributed counting24fault_tolerant: false # Fail closed if Redis is down2526# Stricter limit for auth endpoints27- name: rate-limiting28instance_name: auth-strict29config:30minute: 531second: 132route: login-route3334# Request size limit — prevent payload-based DoS35- name: request-size-limiting36config:37allowed_payload_size: 1 # 1 MB max3839# Security headers40- name: response-transformer41config:42add:43headers:44- "X-Content-Type-Options: nosniff"45- "X-Frame-Options: DENY"46- "Strict-Transport-Security: max-age=31536000"
APIs must validate all input — not just for type correctness but for security. Invalid input can cause injection attacks, SSRF, path traversal, and business logic abuse.
Input validation rules
Mass assignment: never bind request body directly to your data model
If your ORM or framework automatically maps JSON body fields to model properties, an attacker can set fields they should not have access to (e.g., isAdmin: true, balance: 999999). Always use an explicit allowlist of fields that are permitted to be set via each endpoint.
Old API versions are a major attack surface. OWASP API9 (Improper Inventory Management) is consistently exploited because organisations lose track of what APIs they expose.
API inventory best practices
API security is a core topic in backend engineering interviews, security architecture reviews, and any role where you design or review APIs. BOLA/IDOR is almost always mentioned.
Common questions:
Strong answer: Explains the difference between authentication and authorisation, knows BOLA by name, mentions rate limiting at the gateway layer, and understands mass assignment.
Red flags: Thinking authentication alone is sufficient for API security, not knowing what BOLA means, or suggesting that HTTPS prevents all API attacks.
Quick check · API Security
1 / 3
Key takeaways
Explain BOLA with a real code example and how to fix it.
BOLA (Broken Object Level Authorization) occurs when an API accepts a user-controlled resource ID without verifying the caller owns that resource. Example: GET /api/orders/1234 — if any authenticated user can access any order ID, an attacker can enumerate all orders by incrementing the ID. Fix: include ownership in the query — SELECT * FROM orders WHERE id = ? AND user_id = ?. Return 404 (not 403) if not found to avoid confirming the resource exists. Use non-sequential UUIDs to make enumeration impractical even without the fix.
What is the difference between API2 (Broken Authentication) and API5 (Broken Function Level Authorization)?
API2 (Broken Authentication) is about identity verification failing — weak tokens, no expiry, no signature validation, missing MFA. The API cannot reliably determine who the caller is. API5 (Broken Function Level Authorization) assumes authentication works, but checks whether a normal user can call admin functions — DELETE /admin/users, POST /admin/config. The caller is correctly identified, but the role/permission check for the specific operation is missing or misconfigured.
From the books
The Web Application Hacker's Handbook (Stuttard & Pinto)
Foundational text covering API and web application attack techniques from the attacker's perspective. Understanding how attacks work is essential for building effective defences.
OWASP API Security Project (owasp.org/api-security)
The authoritative reference for API security vulnerabilities and mitigations. The Top 10 list is updated regularly and includes detailed attack scenarios and prevention guidance.
💡 Analogy
A bouncer, a guest list, and a drink ticket system
⚡ Core Idea
Authentication is the bouncer checking your ID. Authorisation is the guest list — even if you got past the bouncer, some areas require a VIP wristband. Rate limiting is the drink ticket system — you get N tickets, then you wait. All three must work together: a bouncer with no guest list or a guest list with no bouncer are both failures.
🎯 Why It Matters
APIs are the primary interface to your application's data and business logic. A single BOLA bug can expose every user's data. A missing rate limit allows your entire database to be scraped in hours. API security is not optional — it is the security layer for the modern web.
Ready to see how this works in the cloud?
Switch to Career Paths for structured paths (e.g. Developer, DevOps) and provider-specific lessons.
View role-based pathsSign in to track your progress and mark lessons complete.
Questions? Discuss in the community or start a thread below.
Join DiscordSign in to start or join a thread.