API Security
APIs are the backbone of modern applications. Protecting REST and GraphQL endpoints against unauthorized access, code injection and abuse is fundamental to application security.
OWASP API Security Top 10
1. Broken Object Level Authorization
Flaws that allow access to other users' objects by manipulating IDs in requests.
- Always validate that the user has permission to access the requested resource
- Use random identifiers (UUID) instead of sequential IDs
- Implement automated authorization tests
2. Broken Authentication
Vulnerabilities in authentication mechanisms that allow impersonation of other users.
- Implement MFA (Multi-Factor Authentication)
- Use tokens with short expiration time
- Implement rate limiting on login endpoints
- Validate tokens on all requests
3. Broken Object Property Level Authorization
Exposure or modification of properties that should be restricted (mass assignment).
4. Unrestricted Resource Consumption
Lack of limits on requests allowing DoS and excessive resource consumption.
5. Broken Function Level Authorization
Users accessing administrative functions by manipulating endpoints.
Authentication and Authorization
OAuth 2.0
Industry-standard authorization framework for access delegation.
- Authorization Code Flow: For server-side web applications
- PKCE: Proof Key for Code Exchange for SPAs and mobile
- Client Credentials: For machine-to-machine communication
- Refresh Tokens: To maintain sessions without re-authentication
JSON Web Tokens (JWT)
- Use secure algorithms (RS256, ES256) instead of HS256 when possible
- Validate issuer (iss), audience (aud) and expiration (exp)
- Do not store sensitive data in the payload (JWT is decodable)
- Implement token rotation and blacklisting for logout
- Use short-lived access tokens (15 min) with refresh tokens
API Keys
- Use for service authentication, not end users
- Rotate keys periodically
- Implement different permission levels per key
- Monitor usage and detect anomalies
Rate Limiting and Throttling
Rate Limiting Strategies
- Fixed Window: Fixed limit per time window (e.g., 100 req/min)
- Sliding Window: More precise sliding window
- Token Bucket: Allows controlled bursts
- Leaky Bucket: Processes requests at a constant rate
Implementation
- Different limits per endpoint and user tier
- Informative headers: X-RateLimit-Limit, X-RateLimit-Remaining
- 429 Too Many Requests response with Retry-After header
- Use Redis for distributed counter storage
API Gateways
Centralized layer to manage, monitor and protect APIs.
Key Features
- Authentication & Authorization: Centralized validation
- Rate Limiting: Protection against abuse
- Request/Response Transformation: Format adaptation
- Logging & Monitoring: Complete visibility
- Caching: Performance improvement
- Load Balancing: Load distribution
Popular Solutions
- Kong: Open-source gateway based on Nginx
- AWS API Gateway: AWS managed solution
- Apigee: Google's enterprise platform
- Azure API Management: Microsoft's gateway
- Tyk: Open-source gateway in Go
REST vs GraphQL Security
REST API Security
- Use versioning (/v1/, /v2/) for backward compatibility
- Implement HATEOAS for resource discovery
- Validate Content-Type and Accept headers
- Use HTTPS exclusively
- Implement CORS properly
GraphQL Security
- Query Depth Limiting: Prevent recursive queries
- Query Complexity Analysis: Calculate cost before executing
- Disable Introspection: In production, disable schema introspection
- Field-Level Authorization: Control access per field
- Persistent Queries: Whitelist of allowed queries
Input Validation and Sanitization
Input Validation
- Validate type, format, length and range of all inputs
- Use schemas (JSON Schema, OpenAPI) for automatic validation
- Whitelist accepted values when possible
- Reject requests with invalid data (fail securely)
Injection Prevention
- SQL Injection: Use prepared statements and ORMs
- NoSQL Injection: Validate and sanitize queries
- Command Injection: Avoid executing system commands
- LDAP Injection: Escape special characters
Monitoring and Logging
Essential Logs
- All authentication attempts (success and failure)
- Changes to sensitive data
- Authorization failures
- Rate limiting violations
- Errors and exceptions
Security Metrics
- Request rate per endpoint
- Latency and timeouts
- Status codes (especially 401, 403, 429)
- Abnormal traffic patterns
Best Practices
- Use HTTPS/TLS 1.3 exclusively
- Implement security headers (HSTS, CSP, X-Frame-Options)
- Version APIs to allow safe updates
- Document APIs with OpenAPI/Swagger
- Implement health checks and graceful degradation
- Use UUIDs instead of sequential IDs
- Do not expose stack traces or detailed error messages
- Implement timeouts on all operations
- Perform automated security tests (DAST)
Testing Tools
- Postman: Manual and automated API testing
- Burp Suite: Proxy and vulnerability scanner
- OWASP ZAP: Open-source automatic scanner
- Insomnia: REST and GraphQL client
- GraphQL Voyager: GraphQL schema visualization
API security requires a multi-layered approach, combining robust authentication, granular authorization, rigorous input validation, rate limiting, continuous monitoring and regular testing. With APIs increasingly becoming the primary target of attacks, investing in security from the design stage is fundamental to protecting data and maintaining user trust.
