Implement robust API security with OAuth 2.0, JWT validation, rate limiting, input sanitization, and defense-in-depth strategies tailored to your API architecture.
## ROLE
You are an API security specialist with deep expertise in authentication protocols (OAuth 2.0, OpenID Connect, API keys, mTLS), authorization patterns (RBAC, ABAC, ReBAC), and API gateway security. You have secured APIs processing millions of requests per day for [INDUSTRY: fintech / healthcare / e-commerce / SaaS / government].
## OBJECTIVE
Design and implement a comprehensive API security strategy for [API NAME], a [API STYLE: REST / GraphQL / gRPC / WebSocket] API built with [FRAMEWORK: Express.js / FastAPI / Spring Boot / ASP.NET / Go Gin / Rails / Laravel] serving [CONSUMER TYPE: mobile apps / SPAs / third-party developers / internal microservices / IoT devices / partner integrations]. The API handles [DATA CLASSIFICATION: public / internal / confidential / restricted] data and must comply with [COMPLIANCE: SOC 2 / PCI DSS / HIPAA / GDPR / none specific].
## TASK
### Authentication Architecture
Design a multi-layered authentication system:
**Primary Authentication Method: [CHOOSE ONE]**
**Option A — OAuth 2.0 + OIDC (for user-facing APIs):**
- Authorization server: [PROVIDER: Auth0 / Okta / Keycloak / Cognito / custom]
- Grant types enabled:
- Authorization Code + PKCE for [SPA/MOBILE CLIENTS] (NEVER implicit grant)
- Client Credentials for [SERVICE-TO-SERVICE] communication
- Device Authorization for [IOT/TV CLIENTS] if applicable
- NEVER Resource Owner Password Credentials (deprecated, insecure)
- Token configuration:
- Access token format: [JWT / opaque reference token]
- Access token lifetime: [DURATION: 5 min / 15 min / 1 hour] — shorter for higher sensitivity
- Refresh token lifetime: [DURATION: 7 days / 30 days] with absolute expiry
- Refresh token rotation: enabled (one-time use, new refresh token issued each time)
- Token binding to [CLIENT FINGERPRINT: DPoP proof / client certificate thumbprint] if high security
**Option B — API Key + HMAC (for developer APIs):**
- Key generation: Cryptographically random, minimum 256 bits, prefixed with [ENVIRONMENT INDICATOR: pk_live_ / pk_test_]
- HMAC signature: Sign each request with [ALGORITHM: HMAC-SHA256] over [SIGNED ELEMENTS: timestamp + method + path + body hash]
- Timestamp validation: Reject requests older than [WINDOW: 5 minutes] to prevent replay attacks
- Key scoping: Each key restricted to [SCOPE: specific endpoints / rate tier / IP allowlist]
**Option C — mTLS (for service-to-service):**
- Certificate authority: [INTERNAL CA / SERVICE MESH CA / SPIFFE/SPIRE]
- Certificate rotation: [FREQUENCY: 24 hours / 7 days / 30 days]
- SPIFFE ID format for service identity verification
- Certificate pinning strategy for known consumers
### JWT Validation Implementation
If using JWT access tokens, implement comprehensive validation in [LANGUAGE]:
```
JWT Validation Checklist:
1. Verify signature using [ALGORITHM: RS256 / ES256] — NEVER HS256 with public clients
2. Validate issuer (iss) matches [EXPECTED ISSUER URL]
3. Validate audience (aud) matches [YOUR API IDENTIFIER]
4. Check expiration (exp) — reject expired tokens with clock skew tolerance of [SECONDS: 30]
5. Check not-before (nbf) if present
6. Validate token ID (jti) against revocation list or replay cache
7. Extract and validate custom claims: [CUSTOM CLAIMS: roles / permissions / tenant_id / subscription_tier]
8. Verify token type (typ) header to prevent token confusion attacks
9. JWKS endpoint caching with [TTL: 1 hour] and forced refresh on signature failure
10. Key rotation handling: Accept tokens signed by previous key for [GRACE PERIOD]
```
### Authorization Layer
Implement fine-grained authorization:
**[AUTHORIZATION MODEL: RBAC / ABAC / ReBAC] Design:**
- Define roles: [ROLES: admin / manager / member / viewer / service-account / api-consumer]
- Permission matrix: Map each role to allowed [HTTP METHODS] on each [RESOURCE PATH]
- Resource-level access: Ensure users can only access [RESOURCES] belonging to their [TENANT / ORGANIZATION / TEAM]
- Field-level access: Sensitive fields [FIELDS: SSN / credit_card / salary / medical_records] filtered based on [PERMISSION LEVEL]
- Evaluate authorization AFTER authentication but BEFORE any business logic or database queries
### Input Validation and Sanitization
Protect every input surface:
- **Path parameters**: Validate format ([UUID / INTEGER / SLUG]) and reject traversal attempts
- **Query parameters**: Whitelist allowed parameters, validate types, enforce maximum lengths
- **Request body**: Validate against [SCHEMA VALIDATION: JSON Schema / Zod / Joi / Pydantic / class-validator] with strict mode (reject unknown properties)
- **Headers**: Validate Content-Type, reject unexpected content types, size limits on custom headers
- **File uploads**: Validate MIME type (check magic bytes, not just extension), enforce [MAX SIZE], scan with [ANTIVIRUS: ClamAV] before processing, store outside web root
- **GraphQL-specific**: Query depth limiting ([MAX DEPTH: 10]), query complexity analysis ([MAX COST: 1000]), disable introspection in production
### Rate Limiting and Throttling
Implement tiered rate limiting:
```
Rate Limit Tiers:
- Global: [REQUESTS] per [WINDOW] across all consumers
- Per-consumer: [REQUESTS] per [WINDOW] identified by [API KEY / JWT SUB / IP]
- Per-endpoint: [CRITICAL ENDPOINTS] limited to [REQUESTS] per [WINDOW]
- Burst allowance: [BURST SIZE] requests above limit before throttling
- Cost-based: [EXPENSIVE OPERATIONS: search / export / bulk create] count as [MULTIPLIER]x
Response headers:
- X-RateLimit-Limit: Maximum requests allowed
- X-RateLimit-Remaining: Requests remaining in window
- X-RateLimit-Reset: Unix timestamp when window resets
- Retry-After: Seconds to wait when rate limited (429 response)
```
Backend implementation using [RATE LIMITER: Redis sliding window / token bucket / leaky bucket / fixed window with distributed counter].
### API Gateway Security
Configure [API GATEWAY: Kong / AWS API Gateway / Apigee / Cloudflare / Nginx / Traefik]:
- TLS 1.3 enforcement with strong cipher suites
- Request size limits: [MAX BODY SIZE: 1MB / 10MB / custom]
- Timeout configuration: [CONNECTION: 5s] [READ: 30s] [WRITE: 30s]
- IP allowlisting for [RESTRICTED ENDPOINTS: admin / webhooks / internal]
- Geographic restrictions if applicable: [ALLOWED REGIONS]
- WAF rules for common attack patterns (SQLi, XSS, path traversal, protocol attacks)
- Bot detection and challenge mechanisms for public endpoints
### Security Response Headers
Configure all responses with:
```
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Type: application/json; charset=utf-8
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Cache-Control: no-store, no-cache, must-revalidate, private
X-Request-ID: [CORRELATION ID for tracing]
```
### Error Handling
Standardize error responses to prevent information leakage:
- Never expose stack traces, internal paths, database errors, or framework versions
- Use consistent error format: `{ "error": { "code": "[ERROR_CODE]", "message": "[USER_SAFE_MESSAGE]", "request_id": "[TRACE_ID]" } }`
- Log detailed error context server-side, return generic messages client-side
- Differentiate between 401 (not authenticated) and 403 (not authorized) correctly
- Return 404 instead of 403 for resources the user should not know exist
### Logging and Monitoring
Log every API request with:
- Timestamp, request ID, client IP, user agent
- Authenticated identity (user ID, API key prefix — never full key)
- HTTP method, path, query parameters (sanitized), response status, latency
- Alert on: unusual error rate spikes, authentication failure patterns, access to deprecated endpoints, response time anomalies
- Dashboard metrics: requests by consumer, error rates, authentication failures, rate limit hits, p95/p99 latencyOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
{ "error": { "code": "[ERROR_CODE]", "message": "[USER_SAFE_MESSAGE]", "request_id": "[TRACE_ID]" }[API NAME][CHOOSE ONE][LANGUAGE][EXPECTED ISSUER URL][YOUR API IDENTIFIER][GRACE PERIOD][HTTP METHODS][RESOURCE PATH][RESOURCES][PERMISSION LEVEL][MAX SIZE][REQUESTS][WINDOW][CRITICAL ENDPOINTS][BURST SIZE][MULTIPLIER][ALLOWED REGIONS][ERROR_CODE][USER_SAFE_MESSAGE][TRACE_ID]