API Security Best Practices: Protecting Modern Web APIs from Real Attacks
A practical security guide for API developers — covering authentication, authorization, input validation, injection prevention, rate limiting, logging, CORS configuration, and securing third-party integrations against the OWASP API Security Top 10.

Why API Security Deserves Dedicated Attention#
APIs are the primary attack surface for modern web applications. Unlike server-rendered HTML applications where user interactions are mediated through a browser's security model, APIs are directly accessible to any HTTP client — including automated attack tools.
The OWASP API Security Top 10 documents the most commonly exploited API vulnerabilities based on real-world incidents. This guide covers each category with practical mitigation strategies.
Authentication & Authorization Foundations#
Authentication: Verifying Identity Every API endpoint that accesses user data or performs mutations must verify the caller's identity. The two primary mechanisms:
- Bearer Tokens (JWTs): The client includes an Authorization: Bearer
header. The server validates the token's signature and expiry. JWTs are stateless but cannot be instantly revoked. - Session Tokens: An opaque identifier stored in an HttpOnly cookie. The server looks up session data on each request. Instantly revocable but requires server-side session storage.
Authorization: Verifying Permission Authentication proves who you are. Authorization proves what you are allowed to do. These are separate concerns and must be enforced separately.
Broken Object Level Authorization (BOLA) is the most commonly exploited API vulnerability. It occurs when an API endpoint allows users to access other users' objects by manipulating identifiers.
Example vulnerable endpoint: GET /api/invoices/12345 — if any authenticated user can access any invoice by knowing the ID, this is BOLA. The fix: always verify that the requesting user owns or has explicit permission to access the specific object being requested.
Input Validation and Injection Prevention#
Never trust input from API clients. Validate every field in every request:
- Schema validation: Use Zod, Joi, or JSON Schema to declare the exact shape, types, and constraints of expected input. Reject requests that don't conform before touching business logic.
- SQL Injection prevention: Always use parameterized queries or ORM-generated queries. Never concatenate user input into SQL strings.
- NoSQL Injection: Validate and sanitize MongoDB query operators — user-controlled operators like
$wherecan execute arbitrary JavaScript. - Command Injection: Never pass user input to shell commands. If shell execution is unavoidable, use explicit allow-lists and sanitization.
Rate Limiting and Abuse Prevention#
- Credential stuffing (automated login attempts)
- Data scraping (systematic enumeration of your dataset)
- DoS via expensive operations (complex queries, file processing)
- Global rate limit: Maximum requests per IP per minute (prevents naive DoS)
- Endpoint rate limit: Stricter limits on expensive or sensitive endpoints (login: 5/minute, password reset: 3/hour)
- User-level rate limit: Prevents authenticated abuse even from legitimate users
Return standard HTTP 429 Too Many Requests with a Retry-After header when limits are exceeded.
CORS Configuration#
CORS (Cross-Origin Resource Sharing) prevents browsers from making unauthorized cross-origin API requests. Key configuration rules:
- Never use
Access-Control-Allow-Origin: *for APIs that handle authenticated data - Maintain an explicit allow-list of permitted origins
- Do not reflect the Origin header back without validation — this is equivalent to allowing all origins
- Specify
Access-Control-Allow-MethodsandAccess-Control-Allow-Headersexplicitly
Security Headers for APIs#
Even for JSON APIs, security headers prevent certain attack vectors:
Content-Type: application/json— specify the response content type explicitlyX-Content-Type-Options: nosniff— prevent MIME type sniffingStrict-Transport-Security— enforce HTTPS connections- Remove
X-Powered-Byheaders that reveal your technology stack
Logging and Monitoring for Security#
Security without observability is incomplete. Log the following for every API request:
- Timestamp, request ID, authenticated user ID (not PII like email)
- HTTP method, path, status code, response time
- IP address and User-Agent for abuse pattern detection
- Authentication failures (failed login, expired token, invalid signature)
- Passwords, tokens, or API keys
- Full request bodies containing sensitive user data (PCI, HIPAA compliance)
- Query parameters containing credentials
Alert on authentication failure spikes, unusual access patterns, and requests for non-existent resources (potential enumeration attacks).

Published by
Vyuhantrix Team
Security Engineering · Vyuhantrix
Vyuhantrix is an open technology learning platform based in Ahmedabad, India, publishing step-by-step programming tutorials, system design breakdowns, and free developer tools.
Keep Learning
Recommended Guides
The Definitive Full-Stack Web Development Roadmap (2026 Edition)
A complete step-by-step masterclass covering modern HTML5/CSS, TypeScript, Next.js App Router, Server Components, API Design, and Cloud Edge Deployments.
System Design Fundamentals: Building Scalable & Resilient Distributed Systems
Learn how to architect high-availability applications, manage load balancing, configure caching layers, and implement fault-tolerant databases.
Microservices vs. Monolith: An Honest Architecture Decision Guide for 2026
A thorough analysis of when to choose microservices versus a monolithic architecture — covering organizational readiness, operational complexity, data consistency, service boundaries, and the strangler pattern for incremental migration.