API Security
APIs are the connective tissue of modern applications โ they expose business logic, exchange sensitive data, and integrate third-party services. A compromised API can bypass every perimeter control in place. This guide aligns to NIST SP 800-204 (Security Strategies for Microservices-based Application Systems), NIST SP 800-95 (Guide to Secure Web Services), and NIST SP 800-53 Rev 5, and incorporates the OWASP API Security Top 10 (2023).
1. Authentication
Every API request must be authenticated. Anonymous access should be an explicit, audited decision โ not the default.
API Keys
Suitable for server-to-server communication where the client environment is controlled.
| Requirement | Detail |
|---|---|
| Entropy | Minimum 128 bits, cryptographically random |
| Transmission | HTTPS only; never in query strings (logged by proxies) |
| Storage | Hash with SHA-256 before persisting; store only the hash |
| Rotation | Enforce rotation every 90 days or on personnel change |
| Scope | Issue per-service keys; never share a key across consumers |
Authorization: ApiKey <key>
Avoid ?api_key= in URLs. Query parameters appear in server logs, browser history, and referrer headers.
OAuth 2.0 / OpenID Connect
Use for delegated authorisation where a third party acts on behalf of a user.
| Flow | Use Case |
|---|---|
| Authorization Code + PKCE | User-facing apps (SPA, mobile) |
| Client Credentials | Machine-to-machine (M2M) |
| Device Code | Input-constrained devices |
Token requirements (NIST SP 800-63B ยง4):
- Access tokens: short-lived (โค 15 minutes)
- Refresh tokens: bound to client, rotated on use
- Validate iss, aud, exp, nbf on every request
- Use asymmetric signing (RS256 / ES256) โ avoid HS256 in distributed systems
Mutual TLS (mTLS)
For high-assurance service-to-service authentication. Both parties present certificates, establishing cryptographic proof of identity at the transport layer. Aligns to NIST SP 800-204A service mesh security.
Client โ (presents cert) โ API Gateway โ (validates cert) โ Backend
mTLS is the preferred authentication mechanism for internal microservice APIs.
2. Authorisation
Authentication answers who are you? โ authorisation answers what are you allowed to do?
Principle of Least Privilege (NIST AC-6)
- Issue tokens with minimum required scopes
- Validate scopes on every endpoint, not just at the gateway
- Never infer permissions from data in the request body
Broken Object Level Authorisation (BOLA)
The most exploited API vulnerability (OWASP API1:2023). Occurs when an API accepts a user-supplied identifier and returns or modifies the associated object without verifying the requestor owns it.
# Vulnerable
GET /api/orders/8821 โ attacker changes their order ID to another user's
# Mitigated
GET /api/orders/8821 โ server resolves the order by combining JWT subject + order ID
Mitigation:
- Always authorise at the object level, not just the endpoint level
- Use indirect references (UUIDs, opaque tokens) rather than sequential integers
- Enforce ownership checks server-side regardless of what the client sends
Broken Function Level Authorisation (BFLA)
Horizontal privilege escalation through undocumented or administrative endpoints.
- Disable all endpoints not explicitly required
- Apply role checks at the function level, not only at the router
- Never rely on URL obscurity as an access control
3. Rate Limiting & Throttling
Rate limiting is a NIST SI-17 (Fail-Safe Procedures) and AC-7 (Unsuccessful Login Attempts) control. Without it, APIs are vulnerable to brute-force attacks, credential stuffing, denial of service, and scraping.
Limit Dimensions
Apply limits across multiple dimensions simultaneously:
| Dimension | Example Limit | Purpose |
|---|---|---|
| IP address | 100 req/min | Mitigate scraping, DoS |
| API key / client ID | 1 000 req/min | Per-consumer fairness |
| User account | 10 login attempts/hour | Brute-force protection |
| Endpoint | 5 req/min on /reset-password |
Targeted rate abuse |
| Global | 50 000 req/min | Total capacity protection |
Response Headers
Communicate limits to consumers so clients can self-regulate:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 743
X-RateLimit-Reset: 1720000000
Retry-After: 60
Return HTTP 429 Too Many Requests when a limit is exceeded โ never silently drop requests.
Algorithms
| Algorithm | Behaviour | Best For |
|---|---|---|
| Token bucket | Allows bursts up to bucket size | General-purpose APIs |
| Fixed window | Hard limit per time window | Simple to implement; susceptible to boundary bursts |
| Sliding window | Smooth average over rolling period | High-accuracy limiting |
| Leaky bucket | Constant output rate; queues excess | Downstream protection |
Distributed Rate Limiting
In multi-instance deployments, counters must be stored in a shared cache (Redis, Memcached) โ not in process memory. Per-instance limits result in effective limits that are a multiple of the configured value.
4. Input Validation & Schema Enforcement
NIST SI-10 (Information Input Validation) requires validating all inputs for type, format, length, and range before processing.
API Schema Validation
Define a schema contract and enforce it on every request:
- REST: OpenAPI 3.x (formerly Swagger) โ validate requests against the schema at the gateway
- GraphQL: Schema introspection; disable in production; use query depth/complexity limits
- gRPC: Protocol Buffers provide built-in type enforcement
Validation Rules
| Input Type | Control |
|---|---|
| String fields | Max length; character allow-list; reject null bytes |
| Numeric fields | Min/max range; type enforcement (reject strings) |
| Dates | ISO 8601 format; reject dates outside plausible range |
| Enumerations | Strict allow-list; reject unknown values |
| File uploads | MIME type validation; file size limit; AV scanning |
| JSON bodies | Max depth (prevent deeply nested DoS); max size |
Mass Assignment
Attackers supply additional properties the server never expected to receive.
// Attacker adds "role" to a user-update request
{ "name": "Alice", "email": "alice@example.com", "role": "admin" }
Mitigation: Use an explicit allow-list of accepted properties. Never pass raw request bodies directly to data models (ORM or otherwise).
5. Transport Security
NIST SC-8 mandates cryptographic protection of data in transit.
- TLS 1.3 required; TLS 1.2 acceptable with strong cipher suites
- Disable TLS 1.1 and below
- Enforce HSTS on all API domains:
Strict-Transport-Security: max-age=31536000; includeSubDomains - Pin certificates for high-value internal services (mTLS)
- Never transmit secrets (tokens, keys, passwords) in query parameters
6. API Lifecycle Management
Unmanaged APIs are a leading source of security debt. NIST SP 800-204 emphasises lifecycle controls across design, deployment, and retirement.
Inventory & Discovery
You cannot secure what you do not know exists.
- Maintain a centralised API registry (gateway catalogue, API management platform)
- Run discovery scans to detect shadow APIs not registered in the catalogue
- Include APIs in the CMDB and tie them to owners and data classifications
Versioning
| Practice | Rationale |
|---|---|
Explicit versioning (/v1/, /v2/) |
Allows controlled deprecation without breaking consumers |
| Semantic versioning for breaking changes | Communicate impact clearly |
| Never delete a version without notice | Publish deprecation timelines (โฅ 6 months) |
| Support maximum 2 major versions concurrently | Reduces patching surface |
Deprecation Process
- Announce deprecation date via
DeprecationandSunsetresponse headers - Log and alert when deprecated endpoints are called
- Notify registered consumers directly before shutdown
- Remove the version on the announced date โ do not silently maintain it indefinitely
Deprecation: Sat, 01 Jan 2027 00:00:00 GMT
Sunset: Sat, 01 Jan 2027 00:00:00 GMT
Link: <https://api.example.com/v2/users>; rel="successor-version"
Decommissioning
A decommissioned API that still responds is an attack surface. Ensure:
- Gateway routes removed
- Backend services stopped
- Credentials and tokens revoked
- DNS records removed or redirected
- Audit log retained per data retention policy
7. API Gateway
An API gateway is the primary enforcement point for cross-cutting security controls. Do not rely on each individual service to re-implement authentication, rate limiting, and logging.
Gateway Responsibilities
| Control | Gateway | Service |
|---|---|---|
| TLS termination | โ | โ |
| Authentication (token validation) | โ | Verify claims |
| Rate limiting | โ | โ |
| Schema validation | โ | โ |
| Request/response logging | โ | Business events |
| WAF / DDoS protection | โ | โ |
| Authorisation | Coarse-grained | Fine-grained (BOLA) |
Gateway Security Hardening
- Strip internal headers (
X-Internal-User-ID) before forwarding external requests - Reject requests with unexpected
Hostheaders - Set hard timeouts on upstream connections (prevent slowloris)
- Return generic error messages to callers; log detailed errors internally
- Do not pass raw client errors from upstream services back to callers
8. Logging, Monitoring & Alerting
NIST AU-2 and AU-12 require that APIs generate audit records for security-relevant events.
What to Log
| Event | Fields |
|---|---|
| Every request | Timestamp, method, path, status code, response time, client IP, user/client ID |
| Authentication | Success/failure, credential type, token ID |
| Authorisation failure | Endpoint, user, requested resource, reason |
| Rate limit exceeded | Client ID, endpoint, count |
| Input validation failure | Field, reason (without logging the invalid value if sensitive) |
| Admin / privileged operations | Full audit trail |
What NOT to Log
- Passwords, API keys, or tokens in any field
- Full request bodies containing PII without explicit masking
- Credit card numbers, SSNs, or other regulated data
Detection Patterns
Configure alerts on:
- Spike in 401 / 403 responses (credential stuffing, BOLA probing)
- Spike in 429 responses (rate abuse, DoS)
- Sequential object ID enumeration (incrementing IDs in paths)
- Access to deprecated endpoints (may indicate unpatched client or attacker using old intel)
- Unusual off-hours access patterns
9. OWASP API Security Top 10 (2023)
| # | Vulnerability | Key Mitigation |
|---|---|---|
| API1 | Broken Object Level Authorisation | Authorise every resource access server-side |
| API2 | Broken Authentication | Strong credentials, short-lived tokens, MFA |
| API3 | Broken Object Property Level Authorisation | Allow-list response fields; never over-expose |
| API4 | Unrestricted Resource Consumption | Rate limits, payload size limits, query complexity limits |
| API5 | Broken Function Level Authorisation | Role enforcement at the function level |
| API6 | Unrestricted Access to Sensitive Business Flows | Business-logic rate limits (e.g. checkout, transfers) |
| API7 | Server-Side Request Forgery (SSRF) | Allow-list outbound destinations; block internal IP ranges |
| API8 | Security Misconfiguration | Harden defaults; disable debug endpoints in production |
| API9 | Improper Inventory Management | Maintain API registry; decommission unused versions |
| API10 | Unsafe Consumption of APIs | Validate third-party API responses; enforce TLS |
10. Common Pitfalls
| Mistake | Risk | Correction |
|---|---|---|
| Tokens in query strings | Exposure in logs, referrer headers, browser history | Use Authorization header |
| Verbose error messages | Leak stack traces, file paths, DB schema | Return generic errors; log details internally |
| Disabled authentication in staging | Attackers target staging to exfiltrate data | Apply identical auth controls across all environments |
| Sequential integer IDs | BOLA enumeration | Use UUIDs or opaque identifiers |
| Returning full objects | Over-exposure of sensitive fields | Return only fields the consumer is authorised to see |
| No API versioning | Breaking changes break consumers or force perpetual backward compat | Version from day one |
| Implicit trust of internal callers | Lateral movement once perimeter is breached | Authenticate and authorise all calls, including internal |
| No timeout on upstream calls | Resource exhaustion / slowloris | Enforce connect and read timeouts at the gateway |
API Security Checklist
| Control | Priority | NIST Reference |
|---|---|---|
| All endpoints require authentication | Critical | AC-3, IA-3 |
| OAuth 2.0 / mTLS for service-to-service | Critical | SC-8, IA-9 |
| Authorisation checked at object level (BOLA) | Critical | AC-3 |
| Rate limiting on all public endpoints | High | SI-17, AC-7 |
| TLS 1.2+ enforced; HSTS enabled | Critical | SC-8 |
| OpenAPI schema validated at gateway | High | SI-10 |
| Mass assignment prevented (allow-lists) | High | SI-10 |
| API inventory maintained and audited | High | CM-8 |
| Versioning and deprecation policy defined | High | SA-4 |
| All endpoints logged to centralised SIEM | High | AU-2, AU-12 |
| Tokens never in query parameters | High | SC-28 |
| Debug/introspection endpoints disabled in prod | High | CM-7 |
| OWASP API Top 10 reviewed in threat model | Medium | RA-3 |
| Penetration test APIs annually | Medium | CA-8 |
| Third-party API responses validated | Medium | SI-10 |
Regulatory & Standards Reference
| Standard | Relevance |
|---|---|
| NIST SP 800-204 | Security strategies for microservices and API-driven architectures |
| NIST SP 800-95 | Guide to secure web services (SOAP/REST foundations) |
| NIST SP 800-53 Rev 5 | AC-3, AC-6, AU-2, AU-12, SC-8, SI-10, SI-17 |
| NIST CSF 2.0 | Protect (PR.AA, PR.DS), Detect (DE.CM) |
| OWASP API Security Top 10 (2023) | Practical attack taxonomy |
| PCI DSS 4.0 Req 6.3 | Protect APIs handling cardholder data |
| FAPI 2.0 (Open Banking) | High-security OAuth profiles for financial APIs |