API Security: Scenario-Based Questions
49. How do you design secure APIs that enforce authentication, rate limiting, and input validation?
APIs are the backbone of modern applications β exposing business logic, data, and integrations. Securing them requires a defense-in-depth approach across transport, identity, input, and usage patterns.
π Authentication & Authorization
- Use OAuth 2.0 / OpenID Connect: Issue access tokens with scopes, expiration.
- API Keys: Suitable for internal services or low-risk use β always rotate regularly.
- JWT: Use signed tokens for stateless auth, verify signature and expiry on each request.
- RBAC / ABAC: Enforce granular permissions per resource/action/user.
π Rate Limiting & Abuse Prevention
- Throttling: Apply per-user, per-IP, or per-app limits (e.g., 100 req/min).
- Quota Tracking: Cumulative usage (e.g., daily call limits) per plan tier.
- Leaky Bucket / Token Bucket: Algorithms to handle bursty traffic.
- API Gateways: Use Cloudflare, Kong, Apigee, or AWS API Gateway to enforce limits.
π§Ή Input Validation
- Strong Schema Validation: JSON Schema, Protocol Buffers, OpenAPI specs.
- Sanitize Inputs: Prevent SQLi, XSS, and command injections (e.g., use ORM, encode output).
- Reject Unexpected Fields: Deny payloads with unknown or extra parameters.
- Limit Payload Size: Avoid DoS attacks from large POST bodies.
β Additional Best Practices
- Use HTTPS everywhere β TLS 1.2+ only.
- Set cache headers carefully to avoid exposing sensitive data.
- Log audit trails for sensitive operations.
- Apply CORS policies intentionally and securely.
π« Common Pitfalls
- Trusting client-side validation only.
- Exposing verbose error messages with stack traces or config info.
- Unrestricted access to admin/debug endpoints.
- No expiry/rotation policy for tokens or keys.
π Final Insight
Secure APIs are predictable, minimal, and defensive. Great API security doesnβt just block bad requests β it makes good ones safer and more reliable for the long term.