How to Protect API Endpoints

APIs present unique security challenges requiring specialized protection strategies. This guide covers comprehensive API security using AtomicEdge WAF protection.

Understanding API Security Challenges

APIs differ from traditional web applications:

Characteristics: – No user interface, pure data exchange – JSON/XML payloads instead of HTML forms – Authentication via tokens or API keys – Higher request frequency – Machine-to-machine communication – Often publicly documented

Threats: – Authentication bypass – Authorization flaws – Injection attacks (SQL, NoSQL, command) – Excessive data exposure – Rate limit abuse – Broken object level authorization

Basic API Protection

Enabling WAF Rules

Start with OWASP Core Rule Set:

Configuration:

WAF Protection: Enabled
Rule Groups: OWASP Core Rule Set
Response: 403 Forbidden

Why: OWASP CRS protects against injection attacks and common vulnerabilities without requiring API-specific tuning.

Testing:

# Test API still functions
curl -X GET https://api.example.com/v1/users

# Test SQL injection blocked
curl -X GET "https://api.example.com/v1/users?id=1' OR '1'='1"
# Expected: 403 Forbidden

Rate Limiting APIs

Prevent abuse and resource exhaustion:

Public API (unauthenticated):

Rate Limiting: Enabled
Protected Paths: /api/
Events per minute: 60
Response: 403

Authenticated API:

Rate Limiting: Enabled
Protected Paths: /api/
Events per minute: 300
Response: 403

Tiered Approach:

Free tier: 60 requests/minute
Paid tier: 300 requests/minute (use IP whitelist)
Enterprise: 1000 requests/minute (use IP whitelist)

Authentication and Authorization

Token-Based Authentication

APIs use bearer tokens:

Protection Strategy:

  1. Rate limit authentication endpoints:
Protected Paths: /api/auth/login, /api/auth/token
Events per minute: 10
Response: Drop
  1. Monitor for token abuse:
  2. Watch for single token from many IPs
  3. Check for token reuse patterns
  4. Alert on unusual geographic distribution

  5. Protect token endpoints:

Protected Paths: /api/auth/
Events per minute: 5
Response: Drop

API Key Security

Static API keys require protection:

IP Restriction:

Page Protection: Enabled
Protected Paths: /api/
Whitelist: [client-server-ips]
Response: 403

Considerations: – Rotate keys regularly – One key per client – Monitor key usage – Revoke compromised keys immediately

OAuth Endpoints

OAuth flows need special handling:

Configuration:

Rate Limiting:
  /oauth/authorize: 20 requests/min
  /oauth/token: 10 requests/min
  Response: 403

Monitor For: – Authorization code interception attempts – Token endpoint brute force – Redirect URI manipulation

Protecting Specific API Patterns

REST APIs

Standard REST protection:

Read Operations (GET):

Rate Limiting: 120 requests/min
WAF Rules: OWASP CRS
Response: 403

Write Operations (POST, PUT, DELETE):

Rate Limiting: 60 requests/min
WAF Rules: OWASP CRS + validation
Response: 403

Sensitive Endpoints:

Protected Paths: /api/admin/, /api/users/*/password
Rate Limiting: 10 requests/min
IP Whitelist: [admin-ips]
Response: Drop

GraphQL APIs

GraphQL has unique vulnerabilities:

Configuration:

Protected Paths: /graphql
Rate Limiting: 60 requests/min
WAF Rules: OWASP CRS
Response: 403

Additional Considerations: – Monitor query complexity (application-level) – Limit query depth (application-level) – Watch for introspection abuse – Rate limit per operation type

Example Protection:

# Test normal query works
curl -X POST https://api.example.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ users { id name } }"}'

# Verify rate limiting
for i in {1..100}; do
  curl -s -o /dev/null -w "%{http_code}\n" \
    -X POST https://api.example.com/graphql \
    -H "Content-Type: application/json" \
    -d '{"query":"{ users { id } }"}'
done

WebSocket APIs

Real-time connections need different approach:

Initial Connection:

Protected Paths: /ws, /socket.io/
Rate Limiting: 10 connections/min per IP
Response: Drop

Considerations: – Long-lived connections – Authenticate on connect – Monitor connection count – Limit per user/IP

Webhook Receivers

Incoming webhooks from third parties:

Protection:

Page Protection: Enabled
Protected Paths: /webhooks/
Whitelist: [third-party-service-ips]
Response: 403

Best Practices: – Verify webhook signatures (application-level) – Whitelist known service IPs – Rate limit per source – Log all webhook activity

API-Specific Attack Protection

Injection Attack Protection

SQL, NoSQL, command injection:

WAF Configuration:

OWASP Core Rule Set: Enabled
Disabled Rules: [only as needed for false positives]
Response: 403

Testing:

# SQL injection
curl -X GET "https://api.example.com/v1/users?filter=id%3D1'%20OR%20'1'%3D'1"
# Expected: 403

# NoSQL injection
curl -X POST https://api.example.com/v1/search \
  -H "Content-Type: application/json" \
  -d '{"$where": "sleep(1000)"}'
# Expected: 403

# Command injection
curl -X GET "https://api.example.com/v1/file?name=test;rm%20-rf%20/"
# Expected: 403

Mass Assignment Protection

Prevent unauthorized field updates:

Application-Level: Validate allowed fields

WAF-Level: Monitor for unusual parameter patterns

Configuration:

Monitor logs for:
- POST/PUT with admin/role parameters
- Unusual field names
- Large parameter counts

Excessive Data Exposure

Prevent information leakage:

Application-Level: Implement proper serialization

WAF-Level: – Monitor response sizes – Alert on data dumps – Rate limit export endpoints

Configuration:

Protected Paths: /api/export/, /api/dump/
Rate Limiting: 1 request per 5 minutes
IP Whitelist: [admin-ips]
Response: 403

Broken Object Level Authorization

Users accessing others’ data:

Application-Level: Validate object ownership

WAF-Level: – Rate limit object access – Monitor access patterns – Alert on enumeration

Configuration:

Protected Paths: /api/users/*/private
Rate Limiting: 30 requests/min
Monitor: Sequential ID access patterns

API Documentation Security

Protecting OpenAPI/Swagger

Documentation exposure risks:

Option 1: Restrict Access

Page Protection: Enabled
Protected Paths: /api/docs, /swagger
Whitelist: [office-ips, partner-ips]
Response: 404

Option 2: Public Docs, Protected Endpoints

/api/docs: Public (no protection)
/api/ endpoints: Authenticated, rate limited

Option 3: Separate Documentation Site – Host docs on docs.example.com – Production API has no docs endpoint – Reduces attack surface

Monitoring API Traffic

Key Metrics

Track API health and security:

Request Volume:

Baseline: 1000 requests/hour
Alert: >3000 requests/hour (300% increase)

Error Rates:

Normal: <1% 4xx/5xx
Alert: >5% error rate

Geographic Distribution:

Expected: 80% US, 15% Canada, 5% others
Alert: Unusual countries appear

Response Times:

Normal: <200ms average
Alert: >500ms average (potential attack)

Attack Indicators

Signs of API attack:

Enumeration:

Pattern: /api/users/1, /api/users/2, /api/users/3...
Volume: Hundreds per minute from single IP
Response: 403 or 404 (depending on vulnerability)
Action: Rate limiting + IP block

Token Brute Force:

Pattern: /api/ with different Authorization headers
Volume: Rapid attempts (10+/second)
Response: 401 Unauthorized
Action: Rate limiting authentication endpoints

Parameter Fuzzing:

Pattern: Same endpoint, varying parameters
Volume: Automated tool patterns
Response: Mix of 200, 400, 403
Action: Rate limiting + bot protection

API Version Management

Protecting Legacy Versions

Old API versions may have vulnerabilities:

Option 1: Deprecate

Protected Paths: /api/v1/
Response: 410 Gone
Message: "API v1 deprecated, use v3"

Option 2: Restrict Access

Protected Paths: /api/v1/
IP Whitelist: [legacy-client-ips]
Rate Limiting: 30 requests/min
Response: 403

Option 3: Aggressive Protection

Protected Paths: /api/v1/
WAF Rules: All enabled
Rate Limiting: 10 requests/min
Response: Drop

Version-Specific Configuration

Different protection per version:

v1 (legacy, restricted):

Rate Limiting: 10 requests/min
IP Whitelist: Required
Response: Drop

v2 (current, protected):

Rate Limiting: 60 requests/min
WAF Rules: OWASP CRS
Response: 403

v3 (new, monitored):

Rate Limiting: 120 requests/min
WAF Rules: OWASP CRS
Response: 403
Monitor: Closely for false positives

Client-Specific Protection

Mobile App APIs

Mobile apps have specific patterns:

Configuration:

Protected Paths: /api/mobile/
Rate Limiting: 120 requests/min (higher for frequent polling)
Response: 403

Considerations: – Background sync operations – Retry logic – Poor connectivity – Battery optimization

Third-Party Integrations

Partner API access:

Configuration:

Protected Paths: /api/partner/
IP Whitelist: [partner-ips]
Rate Limiting: 300 requests/min
Response: 403

Monitoring: – Track usage per partner – Alert on unusual patterns – Dedicated API keys – Regular access reviews

Internal APIs

Microservices and internal communication:

Configuration:

Protected Paths: /api/internal/
IP Whitelist: [internal-service-ips]
Response: Drop (unauthorized access = security incident)

Best Practice: Don’t expose internal APIs publicly. Use private network or VPN.

False Positive Management

Common API False Positives

JSON Payloads:

Issue: Complex JSON triggers XSS/SQL rules
Rule: 941xxx (XSS), 942xxx (SQL)
Solution: Disable specific rules for /api/ paths

User-Generated Content:

Issue: API accepts HTML/markdown, triggers XSS
Rule: 941130 (XSS)
Solution: Disable for specific endpoints like /api/posts

Search Queries:

Issue: Search with SQL-like operators triggers blocks
Rule: 942100 (SQL injection)
Solution: Disable for /api/search, use application-level validation

Testing for False Positives

Systematic API testing:

#!/bin/bash
# Test API endpoints

ENDPOINTS=(
  "/api/users"
  "/api/posts"
  "/api/search"
  "/api/auth/login"
)

for endpoint in "${ENDPOINTS[@]}"; do
  echo "Testing $endpoint"
  
  # GET request
  curl -s -o /dev/null -w "GET: %{http_code}\n" \
    "https://api.example.com$endpoint"
  
  # POST with JSON
  curl -s -o /dev/null -w "POST: %{http_code}\n" \
    -X POST "https://api.example.com$endpoint" \
    -H "Content-Type: application/json" \
    -d '{"test":"data"}'
    
  echo "---"
done

Advanced API Protection

Behavioral Analysis

Track API usage patterns:

Baseline Behavior: – Typical request frequency – Common endpoints accessed – Normal parameter ranges – Geographic distribution

Anomaly Detection: – Sudden frequency changes – Unusual endpoint access – Abnormal parameter values – Geographic shifts

Response: – Investigate anomalies – Adjust rate limits – Update whitelist – Alert security team

API Gateway Integration

Combining WAF with API gateway:

Architecture:

Client → AtomicEdge WAF → API Gateway → Backend

Responsibilities: – WAF: Attack blocking, rate limiting, IP filtering – Gateway: Authentication, transformation, routing – Backend: Business logic

Benefits: Layered security, specialized tools for each function.

Troubleshooting

API Blocked Unexpectedly

Diagnosis: 1. Check security logs for rule trigger 2. Review request payload 3. Identify specific rule 4. Determine if legitimate

Common Causes: – JSON with suspicious patterns – SQL-like search queries – HTML in content fields – Special characters in data

Solution: Disable problematic rule for API paths.

Rate Limiting Too Aggressive

Symptoms: Clients hit limits during normal use

Solutions: 1. Increase rate limit by 50-100% 2. Whitelist high-volume client IPs 3. Implement tiered rate limiting 4. Use authentication for higher limits

Performance Impact

Symptoms: API latency increased after protection

Diagnosis: – Measure baseline without WAF – Measure with WAF enabled – Check origin server load

Solutions: – Optimize origin performance – Ensure adequate server resources – Review rule complexity

Best Practices Summary

Layered Security: WAF + authentication + application validation

Appropriate Rate Limits: Balance security and usability

IP Whitelisting: For known clients when possible

Monitoring: Track metrics and alert on anomalies

False Positive Testing: Test thoroughly before production

Documentation: Document API security configuration

Regular Review: Quarterly review of limits and rules

Version Management: Different protection per API version

Client Communication: Notify clients of protection features

Incident Response: Plan for API-specific attacks

API security requires understanding unique API characteristics and applying appropriate protections while maintaining functionality and performance.