APIs move the trust boundary out of the browser and into a public endpoint that attackers can enumerate without installing anything. They are also where most modern applications keep their real logic, which makes a single missing check equivalent to handing over the database. API security rests on four pillars that must each hold: prove who is calling, verify that this caller may touch this specific object, constrain how fast and in what shape requests may arrive, and make sure responses never leak more than the caller needs. Authentication is the pillar teams build first and the one they most often mistake for the whole structure.
The vulnerabilities that keep appearing in API assessments
Every year's breach reports rhyme because the same design errors recur across languages and frameworks. The list below is ordered by how often each appears in real assessments rather than by theoretical severity, which makes it a useful review checklist before any external test.
| Vulnerability | What goes wrong | Primary mitigation |
|---|---|---|
| Broken object-level authorization | Changing an ID in the URL returns another user's record | Server-side ownership check on every read and write |
| Broken function-level authorization | An ordinary token calls an admin endpoint | Role checks enforced per route, not per page |
| Excessive data exposure | Responses include every field the model has | Explicit response schemas, field allowlists |
| Mass assignment | Posting an admin field sets it from a client payload | Named input models that exclude privileged fields |
| Injection | Unvalidated input reaches a query or shell | Parameterized queries, strict type validation |
| Lack of rate limiting | Credential stuffing and scraping run unthrottled | Per-identity and per-IP throttling with backoff |
| Weak token validation | Signature, issuer, or expiry never checked | Full claim verification with pinned algorithms |
Notice that most of these are authorization problems wearing authentication's clothes. A perfectly signed token that is never compared against the resource being requested proves nothing about whether the caller deserves access to it.
Verifying tokens: every claim, every time
Token verification fails in predictable ways: checking only that a signature exists, accepting whichever algorithm the token declares, or ignoring audience and issuer. An attacker who can choose the algorithm can downgrade to none; a token minted for another service becomes valid in yours if audience is not enforced. The implementation below verifies with a pinned algorithm and checks the claims that actually bind a token to this API.
import jwt
import time
from dataclasses import dataclass
PUBLIC_KEY = open("keys/api-public.pem").read()
@dataclass
class Claims:
sub: str
scopes: list
exp: int
def verify_bearer_token(token: str, required_scope: str) -> Claims:
try:
payload = jwt.decode(
token,
key=PUBLIC_KEY,
algorithms=["RS256"], # pinned: never trust the token's own claim
audience="api.example.com",
issuer="https://auth.example.com/",
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.ExpiredSignatureError:
raise PermissionError("token expired")
except jwt.InvalidTokenError as exc:
raise PermissionError(f"invalid token: {exc.__class__.__name__}")
if required_scope not in payload.get("scopes", []):
raise PermissionError("insufficient scope")
if payload["exp"] < time.time():
raise PermissionError("token expired")
return Claims(payload["sub"], payload["scopes"], payload["exp"])
# Example: reject a token that is valid but issued for a different service
try:
claims = verify_bearer_token(bearer_header, "orders:read")
except PermissionError as err:
return_json({"error": "unauthorized"}, status=401)
Rotate keys on a schedule with an overlap window during which both the old and new public keys are accepted, so rotation never causes an outage. Keep access tokens short-lived and refresh them server-side; a long-lived token amplifies every theft.
Object-level authorization on every request
The most damaging API flaw is returning data because the caller is authenticated rather than because the caller owns the record. It is trivially exploitable â change a numeric identifier and see what comes back â and it is invisible to scanners, which is why it stays in production until a researcher reports it. The fix belongs in a repository layer that takes the caller's identity as a required argument, so forgetting the check becomes a type error rather than a silent omission.
class OrderRepository:
def get_order(self, order_id: int, caller: Claims) -> "Order":
# Ownership is part of the query, not a later if-statement
row = self.db.query_one(
"SELECT id, customer_id, total, status FROM orders "
"WHERE id = %s AND customer_id = %s",
(order_id, caller.sub),
)
if row is None:
# Do not reveal whether the order exists for someone else
raise NotFound("order")
return Order.from_row(row)
def update_order_status(order_id: int, status: str, caller: Claims):
if "orders:write" not in caller.scopes:
raise Forbidden("scope required")
order = order_repository.get_order(order_id, caller)
if order.status == "shipped":
raise Conflict("order already shipped")
audit_log.record(actor=caller.sub, action="status_change",
order=order_id, from_order=order.status, to_order=status)
order.status = status
order_repository.save(order)
Return the same 404 for "does not exist" and "belongs to someone else." Distinguishing them confirms which identifiers are valid and turns an enumeration problem into an information leak. Write the ownership predicate into the repository interface itself, then add an integration test per resource that asserts a second user's token cannot read the first user's object.
Rate limiting: a token bucket, not a counter
Fixed-window counters burst at window boundaries and punish legitimate retries, while a token bucket permits normal bursts but caps sustained throughput. Rate limits should be keyed at two levels â per identity for abuse of the service and per source address for credential stuffing that has not authenticated yet â and they should return the standard headers that let well-behaved clients back off instead of retrying blindly.
import time
import threading
class TokenBucket:
def __init__(self, rate_per_sec: float, capacity: int):
self.rate = rate_per_sec
self.capacity = capacity
self.tokens = float(capacity)
self.updated = time.monotonic()
self.lock = threading.Lock()
def allow(self, cost: int = 1) -> tuple[bool, int, float]:
with self.lock:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
retry_after = 0.0
if self.tokens >= cost:
self.tokens -= cost
return True, int(self.tokens), retry_after
retry_after = (cost - self.tokens) / self.rate
return False, 0, retry_after
def enforce_limit(bucket: TokenBucket, response):
allowed, remaining, retry_after = bucket.allow()
response.headers["X-RateLimit-Remaining"] = str(remaining)
if not allowed:
response.headers["Retry-After"] = str(max(1, int(retry_after + 0.999)))
return response.json({"error": "rate limit exceeded"}, status=429)
return allowed
# Login route: tight bucket per source address
login_bucket = TokenBucket(rate_per_sec=0.2, capacity=5) # 5 immediate tries, then 1 per 5s
Choose the capacity from your traffic data rather than intuition: allow the legitimate peak burst, then set the sustained rate below what an attacker would need to succeed at guessing. Exempt nothing from limits entirely; internal service-to-service calls should have their own bucket with a much higher ceiling.
Endpoint inventory: find the API you forgot you shipped
Authorization checks are worthless on routes nobody knows exist. Shadow endpoints appear when a debugging handler is left in production, an old version stays reachable after a rewrite, and an internal utility route is exposed by a permissive gateway rule. Assessments routinely find administration paths that were never registered in documentation because the framework mounts them automatically. The defense is an inventory generated from the running application rather than from a wiki, then compared against a documented allowlist on every deployment.
# Build an endpoint inventory from the live application object
def inventory(app) -> list[dict]:
routes = []
for rule in app.url_map.iter_rules():
if rule.endpoint == "static":
continue
methods = sorted(m for m in rule.methods if m not in ("HEAD", "OPTIONS"))
handler = app.view_functions.get(rule.endpoint)
auth = getattr(handler, "required_scopes", ["unauthenticated"])
owner = getattr(handler, "owner", "unassigned")
routes.append({
"path": rule.rule,
"methods": methods,
"scopes": auth,
"owner": owner,
"deprecated": getattr(handler, "deprecated", False),
})
return sorted(routes, key=lambda r: r["path"])
def diff_against_documented(routes, documented: set[str]):
live = {r["path"] for r in routes}
return {
"undocumented": sorted(live - documented),
"removed_but_documented": sorted(documented - live),
"no_owner": [r["path"] for r in routes if r["owner"] == "unassigned"],
"deprecated_still_public": [r["path"] for r in routes
if r["deprecated"] and r["scopes"] == ["unauthenticated"]],
}
Fail the deployment when the diff reports an undocumented route, a route with no owner, or a deprecated path still reachable without authentication. Those three conditions account for most of the surprising surface an external test finds, and catching them in the pipeline is considerably cheaper than discovering them in a report. Keep the documented list in version control next to the gateway configuration so the review happens where the change is made rather than in a separate tool nobody opens.
Validate the shape of every payload
Schemas are the boundary where untrusted text becomes typed data. Validating strictly means rejecting unknown fields rather than silently discarding them, because a silently dropped is_admin field teaches nobody that the client sent it. The models below demonstrate allowlist validation for identifiers, type and range checks for numbers, and rejection of properties that do not belong to the contract.
from pydantic import BaseModel, EmailStr, Field, ValidationError
class CreateUser(BaseModel):
username: str = Field(min_length=3, max_length=32, pattern=r"^[a-zA-Z0-9_]+$")
email: EmailStr
age: int = Field(ge=13, le=120)
newsletter: bool = False
class Config:
extra = "forbid" # unknown fields raise instead of vanishing
def handle_create(payload: dict):
try:
user = CreateUser.model_validate(payload)
except ValidationError as exc:
return {"error": "validation failed",
"fields": [f["loc"] for f in exc.errors()]}, 400
# Persist only the named fields; privileged columns never appear here
return user_repo.create(user.username, user.email, user.age, user.newsletter)
Pair schema validation with output filtering: serialize responses through an explicit response model so a field added to the database does not automatically appear on the public API. Then set headers that constrain what a browser will do with whatever slips through.
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
X-Content-Type-Options: nosniff
Cache-Control: no-store
X-RateLimit-Limit: 100
Cache-Control: no-store matters more than it looks: shared proxies caching a personalized response will happily serve one caller's data to the next.
đTest authorization, not just authentication
Common Mistakes
Treating a valid signature as proof of authorization
Fix: Pass the caller identity into every repository query so ownership is enforced by the data access layer.
Trusting the algorithm declared inside the JWT header
Fix: Pin the algorithm on the server and require exp, iss, aud, and sub claims explicitly.
Returning different errors for missing versus forbidden resources
Fix: Return the same 404 for both so identifiers cannot be enumerated by probing.
Rate limiting only after authentication succeeds
Fix: Apply a tight per-address bucket to login and token endpoints, and a separate per-identity bucket for application traffic.
Serializing model objects directly and exposing every column
Fix: Serialize through an explicit response schema and reject unknown input fields instead of dropping them silently.
Best Practices
- Enforce object-level and function-level authorization on the server for every single request.
- Keep access tokens short-lived, pin the verification algorithm, and rotate signing keys with an overlap window.
- Combine per-identity and per-source rate limits, and return Retry-After so clients back off correctly.
- Validate input against a strict schema with extra fields forbidden, and filter output through a named response model.
- Log every authorization failure with the caller and target resource; a spike is your earliest breach signal.
Key Takeaways
- Authentication answers who the caller is; authorization answers whether this caller may touch this object â and only the second one prevents data breaches.
- Object-level authorization must live in the data access layer, not in scattered conditional checks.
- Token buckets give sensible burst behavior while capping sustained abuse, at two different key scopes.
- Strict schema validation and output filtering close mass assignment and excessive data exposure at once.
- Rate limits, security headers, and audit logging form the abuse-prevention layer that survives even correct authorization.