Lesson 7 of 10
API Security
APIs are the backbone of modern applications - and the primary attack surface. OWASP maintains a dedicated API Security Top 10 list that addresses vulnerabilities unique to API-based architectures.
OWASP API Security Top 10
API1 - Broken Object Level Authorization (BOLA/IDOR):
GET /api/v1/accounts/12345 (logged in as user owning account 99999)
→ Returns account 12345's data - attacker iterates numeric IDs
Fix: Server must verify: does the authenticated user OWN this resource?
API2 - Broken Authentication:
Weak API keys, predictable session tokens, missing token validation
Fix: JWT with proper validation, rate limiting, token expiry
API3 - Broken Object Property Level Authorization:
GET /api/user/profile returns: {"name": "Alice", "role": "admin", "salary": 120000}
API returns properties the user should not have access to
Fix: Use explicit response schemas - only include fields the caller is authorized to see
API4 - Unrestricted Resource Consumption:
No rate limiting → attacker can exhaust API with unlimited queries
No pagination limits → SELECT * from huge table with no LIMIT
Fix: Rate limiting, pagination, query complexity limits (GraphQL)
API5 - Broken Function Level Authorization:
GET /api/user/orders → OK for regular user
DELETE /api/admin/users/42 → Should require admin role, but doesn't check
Fix: RBAC enforcement on every endpoint, not just UI
API6 - Unrestricted Access to Sensitive Business Flows:
Add item to cart → unlimited without CAPTCHA → inventory exhaustion
Password reset → no rate limit → enumeration of valid emails
Fix: Rate limiting, CAPTCHA, business logic validation
API8 - Security Misconfiguration:
CORS: Access-Control-Allow-Origin: * with credentials
Verbose errors exposing stack traces
HTTP instead of HTTPS, missing security headers
API9 - Improper Inventory Management:
Undocumented /v1 API still running with deprecated security controls
Dev/staging API exposed with production data
Fix: API gateway, versioning strategy, automated discoverySecure API Implementation
# Comprehensive API security in Python (FastAPI)
from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.security import HTTPBearer
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
app = FastAPI()
limiter = Limiter(key_func=get_remote_address)
security = HTTPBearer()
# Rate limiting
@app.get("/api/accounts/{account_id}")
@limiter.limit("30/minute") # 30 requests per minute per IP
async def get_account(
request: Request,
account_id: int,
token: str = Depends(security)
):
# 1. Verify JWT token
current_user = verify_jwt(token.credentials)
# 2. BOLA check - verify ownership (most critical!)
if not db.account_belongs_to_user(account_id, current_user.id):
raise HTTPException(status_code=403, detail="Access denied")
# 403 Forbidden (not 404 - don't reveal existence)
account = db.get_account(account_id)
# 3. Response field filtering - explicit allow list
return {
"id": account.id,
"balance": account.balance,
"name": account.name,
# NEVER return: account.internal_score, account.ssn, account.credit_limit
}
# Security headers middleware
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Content-Security-Policy"] = "default-src 'none'"
return responseCommon Mistakes
- Using sequential integer IDs for resources - enables trivial IDOR enumeration. Use UUIDs (random, unpredictable) for resource IDs - this doesn't fix authorization bugs but raises the bar for enumeration
- No API versioning strategy - without versioning, deprecated endpoints with older security controls remain reachable indefinitely
- Exposing internal API without authentication on internal network - internal APIs are frequently compromised through SSRF and supply chain attacks; authenticate all service-to-service calls
Tip
Tip
Practice API Security in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
OAuth 2.0 + rate limiting.
Practice Task
Note
Practice Task - (1) Write a working example of API Security from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with API Security is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- APIs are the backbone of modern applications - and the primary attack surface.
- Using sequential integer IDs for resources - enables trivial IDOR enumeration. Use UUIDs (random, unpredictable) for resource IDs - this doesn't fix authorization bugs but raises the bar for enumeration
- No API versioning strategy - without versioning, deprecated endpoints with older security controls remain reachable indefinitely
- Exposing internal API without authentication on internal network - internal APIs are frequently compromised through SSRF and supply chain attacks; authenticate all service-to-service calls
Finished this lesson?