API Security: Best Practices for Protection
API документацию (Application Programming Interfaces) have become the foundation of modern web applications. Mobile apps, SPAs, service integrations, and IoT devices all communicate through APIs. But as API usage grows, so does the number of attacks targeting them. In this article, we will cover the key practices for protecting APIs from the most common threats.
Why API Security Matters
According to OWASP, APIs are among the top 10 most vulnerable web application components. The specifics of APIs is that they provide direct access to data and business logic, bypassing the user interface.
Typical consequences of API compromise:
- User personal data leaks
- Unauthorized access to functionality
- Financial losses due to service abuse
- Reputational damage and legal consequences
- Regulatory compliance violations (GDPR, etc.)
Authentication and Authorization
OAuth 2.0 and OpenID Connect
OAuth 2.0 is an authorization standard that allows applications to obtain limited access to user resources without sharing the password. OpenID Connect adds an authentication layer on top of OAuth 2.0.
Key recommendations:
- Use the Authorization Code flow with PKCE for public clients (SPAs, mobile apps)
- Do not use the Implicit Flow — it is deprecated and insecure
- Store tokens securely:
httpOnlycookies for web apps, secure storage for mobile - Set short access token lifetimes (15–30 minutes)
- Implement refresh token rotation
JWT (JSON Web Tokens)
JWT is widely used for transmitting authentication information. However, improper JWT usage creates serious vulnerabilities:
| Mistake | Risk | Solution |
|---|---|---|
| "none" algorithm | Signature bypass | Explicitly specify allowed algorithms |
| Symmetric key (HS256) with a weak secret | Key brute-force | Use RS256/ES256 or a long secret |
| Storage in localStorage | XSS attacks can steal the token | Use httpOnly cookies |
| Missing exp validation | Tokens never expire | Always validate the expiration |
| Sensitive data in payload | Payload is not encrypted, only signed | Don't put passwords or emails in JWT |
API Keys
API keys are suitable for identifying an application but not for authenticating a user. Recommendations:
- Pass keys via the
Authorizationheader or a custom header, not via URL - Implement key revocation and rotation capabilities
- Restrict keys by IP addresses and domains where possible
- Never commit keys to a repository — use environment variables
Rate Limiting
Rate limiting protects APIs from abuse, DDoS attacks, and brute force. Without limits, a single client can overload the server or enumerate all possible values.
Rate Limiting Strategies
- Fixed window — a fixed time window (e.g., 100 requests per minute). Simple to implement, but bursts are possible at window boundaries
- Sliding window — a sliding window for more even distribution
- Token bucket — accumulates "tokens," allowing short bursts. The most flexible approach
- Leaky bucket — stable processing rate with a queue for bursts
Rate Limiting Headers
Inform clients about limits using standard headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1678886400
Retry-After: 30
When the limit is exceeded, return HTTP 429 (Too Many Requests) with a Retry-After header.
CORS — Cross-Origin Resource Sharing
CORS defines which domains can access your API from a browser. Misconfigured CORS is one of the most common API vulnerabilities.
Critically important rules:
- Never use
Access-Control-Allow-Origin: *for APIs with authentication - Maintain an allowlist of permitted domains
- Do not reflect the Origin from the request in the response without validation
- Restrict
Access-Control-Allow-Methodsto only the necessary methods - Set
Access-Control-Max-Ageto cache preflight requests
You can check your API's CORS headers using the enterno.io HTTP header analyzer.
HTTPS and TLS
All API requests must go through SSL/TLS проверку. This is not a recommendation — it is a requirement. HTTP traffic can be intercepted and modified at any point between the client and server.
TLS configuration recommendations:
- Use TLS 1.2 at minimum, preferably TLS 1.3
- Disable deprecated protocols: SSL 3.0, TLS 1.0, TLS 1.1
- Configure HSTS (HTTP Strict Transport Security) with a long
max-age - Use Certificate Pinning for mobile applications
- Regularly verify your SSL configuration using the enterno.io SSL checker
Input Data Validation
Every API request parameter is a potential attack vector. Never trust data from the client.
Validation Rules
- Validate the type, format, length, and range of every parameter
- Use validation schemas (JSON Schema, Zod, Joi, Pydantic)
- Reject requests with unexpected fields
- Sanitize strings to prevent SQL injection and XSS
- Limit request body size
- Validate the Content-Type header
Validation Example with JSON Schema
{
"type": "object",
"required": ["email", "name"],
"properties": {
"email": {
"type": "string",
"format": "email",
"maxLength": 255
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[\\p{L}\\s-]+$"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
}
},
"additionalProperties": false
}
Protection Against Common Attacks
Broken Object Level Authorization (BOLA)
The most prevalent API vulnerability according to the OWASP API Security Top 10. An attacker changes the object ID in a request and gains access to someone else's data.
Defense: verify not only authentication but also authorization for each object. A user with a valid token should not have access to another user's data.
Mass Assignment
The client sends fields it should not be able to modify (e.g., role: "admin" or price: 0). Defense: explicitly define the list of allowed fields for each endpoint.
Excessive Data Exposure
The API returns more data than the client needs, relying on the frontend for filtering. Defense: return only the necessary fields using DTOs (Data Transfer Objects).
Logging and Monitoring
Without adequate logging, you cannot detect an attack or conduct an investigation.
What to log:
- All authentication attempts (successful and failed)
- Access permission changes
- Attempts to access other users' resources
- Rate limit exceeded events
- Input validation errors
- Server errors (500)
What not to log: passwords, tokens, card numbers, personal data in plain text.
API Security Checklist
- All endpoints operate over HTTPS
- Authentication is implemented via OAuth 2.0 or JWT with proper configuration
- Authorization is verified for every resource (BOLA protection)
- Rate limiting is configured on all public endpoints
- CORS correctly restricts allowed domains
- All input data is validated against a schema
- The API does not return excessive data
- Logging covers all important events
- API keys and secrets are stored securely
- API documentation is up to date and does not expose internal architecture
Try It Yourself
Check your API's security headers using the enterno.io HTTP header analyzer — make sure CORS, HSTS, and other headers are configured correctly.
Check your website right now
Check now →