Building Scalable REST APIs (Part 4): Security, Authorization and Abuse Resistance
Secure production REST APIs against broken object authorization, mass assignment, SSRF, resource exhaustion and unsafe integrations with practical patterns for authentication, authorization, validation and abuse controls.

A scalable API that is easy to abuse is not scalable in any useful sense.
Security problems in APIs rarely come from one spectacular cryptographic mistake. More often, they come from ordinary application behaviour that was never given a hostile-input test: accepting an object ID and trusting it, binding a request body directly to a database model, fetching a URL supplied by a customer, returning every field because it was convenient, or allowing an expensive endpoint to be called thousands of times in parallel.
That is why production API security is mostly about enforcing boundaries consistently.
A good REST API should be able to answer four questions for every request:
- Who or what is calling?
- What are they allowed to do?
- Which specific data are they allowed to see or change?
- How much work are they allowed to make the system perform?
This part of the series focuses on those boundaries.
Authentication is only the first gate
Authentication answers who is this caller? Authorization answers may this caller perform this operation on this particular resource?
Those are different jobs.
A valid access token does not mean a user may read any invoice, edit any account or call an administrator endpoint. It only proves whatever identity and claims the issuer intended the token to convey.
This distinction matters because broken authorization remains one of the dominant API security failure modes. The OWASP API Security Top 10 specifically calls out broken object-level authorization, broken object-property authorization and broken function-level authorization.
A dangerous endpoint often looks perfectly normal:
GET /api/orders/8d7f1c52
Authorization: Bearer eyJ...
The bug appears when the server loads the order by ID and returns it without checking that the authenticated principal is allowed to access that order.
Bad:
var order = await repository.GetByIdAsync(id);
return Results.Ok(order);
Better:
var order = await repository.GetForCustomerAsync(
id,
currentUser.CustomerId);
return order is null
? Results.NotFound()
: Results.Ok(order);
In many systems the safest pattern is to make the authorization constraint part of the query itself rather than loading an object and remembering to check ownership later.
Object-level authorization must happen every time
If an endpoint accepts an identifier from the caller, assume it will eventually be changed by an attacker.
UUIDs are not authorization. Random-looking IDs reduce accidental guessing, but they do not establish permission. IDs appear in browser history, logs, exports, emails, analytics systems and support tickets. They also leak through unrelated bugs.
Treat every client-supplied object reference as untrusted.
That includes:
- URL path IDs;
- query-string IDs;
- foreign keys inside JSON bodies;
- IDs embedded in GraphQL-like filters or search payloads;
- file IDs;
- tenant IDs;
- user IDs;
- account IDs;
- organization IDs.
Multi-tenant APIs deserve extra care. A common defensive pattern is to derive the tenant from the authenticated context and never trust a tenant identifier supplied by the client when it can be avoided.
Instead of:
GET /api/tenants/contoso/orders/123
with a query that trusts contoso, prefer a repository call whose tenant scope comes from the authenticated session or token:
SELECT ...
FROM Orders
WHERE Id = @id
AND TenantId = @authenticatedTenantId;
The tenant predicate should be difficult to forget.
Function-level authorization is a separate check
A user may have permission to view an object without having permission to perform every operation on it.
For example:
GET /api/users/42
PATCH /api/users/42
DELETE /api/users/42
POST /api/users/42/reset-password
Those are four different capabilities.
Do not assume that because a caller can read /users/42, they can update or delete it. Role checks, policy checks and resource-specific authorization should reflect the actual business capability.
Useful policy names are usually business-oriented:
CanViewInvoice
CanRefundPayment
CanManageUser
CanExportCustomerData
They age better than checks scattered throughout code such as:
if (user.Role == "Admin" || user.Role == "SuperAdmin" || ...)
Central policy evaluation also makes tests and audits much easier.
Protect object properties, not just objects
Suppose your API accepts:
{
"displayName": "Neil",
"email": "example@example.com",
"isAdmin": true,
"creditLimit": 1000000
}
If the framework binds this directly to your persistence model, an attacker may be able to change properties that were never intended to be writable.
This is often described as mass assignment or over-posting. OWASP now frames the broader problem as broken object property-level authorization.
The fix is not a blacklist of fields. Use explicit input models.
public sealed record UpdateProfileRequest(
string DisplayName,
string Email);
Then map only allowed properties:
user.DisplayName = request.DisplayName;
user.Email = request.Email;
Do the same on output. Your database entity may contain fields that should never leave the service:
PasswordHash
InternalRiskScore
MfaRecoverySecret
StripeCustomerId
FraudNotes
DeletedAt
InternalTenantKey
Returning ORM entities directly from API endpoints makes accidental exposure much easier.
Validate shape, meaning and authority
Input validation has several layers.
Syntactic validation checks whether the request is structurally valid:
email looks like an email
quantity is an integer
currency is a supported code
string length <= 200
Semantic validation checks whether the request makes sense in the domain:
end date is after start date
quantity does not exceed stock
refund amount does not exceed captured amount
Authorization validation checks whether the caller is entitled to make the requested change:
caller owns this address
caller may refund this payment
caller may assign this role
A request can pass the first two and still be malicious.
Use a predictable error contract
Security does not require vague, unusable error handling.
RFC 9457 defines Problem Details for HTTP APIs, giving clients a standard structure for machine-readable errors.
A validation response might look like:
{
"type": "https://api.example.com/problems/validation",
"title": "The request could not be validated",
"status": 400,
"detail": "One or more fields are invalid.",
"errors": {
"email": ["Email address is invalid."]
}
}
For authorization failures, do not leak unnecessary information. Whether to return 403 Forbidden or conceal resource existence with 404 Not Found depends on the threat model and API contract.
The important point is consistency.
Authentication tokens need proper validation
If you accept bearer access tokens, verify them as tokens intended for your API.
Typical checks include:
- signature;
- allowed signing algorithm;
- issuer;
- audience;
- expiration;
- not-before where applicable;
- expected token type/profile;
- required scopes or claims.
Do not decode a JWT, read its claims and assume it is valid. Decoding and validating are different operations.
Do not send bearer tokens in URLs:
/api/report?access_token=...
URLs leak into logs, browser history, monitoring tools and referrer data. Use the Authorization header over TLS.
Scope and role checks are not enough for business authorization
OAuth scopes usually express broad delegated capability:
orders.read
orders.write
payments.refund
They do not normally answer whether the caller can refund this specific payment.
A robust authorization decision can involve several layers:
valid token
+ required scope
+ tenant membership
+ business role
+ ownership/resource policy
+ state transition allowed
For example, a refund might require:
scope = payments.refund
AND caller belongs to merchant
AND payment belongs to merchant
AND payment is captured
AND refund amount <= refundable balance
This is application logic, not something JWT validation can solve by itself.
Rate limiting is a security control as well as a capacity control
Rate limiting is often described as protection against traffic spikes. It also protects sensitive business flows.
Different endpoints deserve different limits.
A cheap public lookup endpoint and a password-reset endpoint should not share the same policy.
Useful dimensions include:
- client IP;
- authenticated account;
- tenant;
- API key;
- endpoint;
- operation cost;
- global capacity.
Example:
GET /catalog 600 requests/minute/account
POST /login 10 requests/minute/IP + account
POST /password-reset 5 requests/hour/account
POST /reports/export 5 concurrent jobs/tenant
POST /checkout business-specific anti-abuse rules
Return 429 Too Many Requests when the limit is exceeded, and where useful provide enough information for a well-behaved client to retry sensibly.
Do not turn limits into a security oracle that exposes sensitive account state.
Resource consumption needs explicit limits
An endpoint may be functionally authorized and still allow a caller to exhaust your infrastructure.
Examples:
GET /api/events?limit=10000000
GET /api/search?from=2000-01-01&to=2030-01-01
POST /api/export
POST /api/images/resize
Set hard limits for expensive operations:
maximum page size
maximum upload size
maximum decompressed body size
maximum filter complexity
maximum date range
maximum export rows
maximum concurrent exports
request timeout/deadline
maximum downstream calls
Queue genuinely expensive work instead of making synchronous HTTP requests wait indefinitely.
A 202 Accepted response with a job resource is often cleaner:
POST /api/exports
HTTP/1.1 202 Accepted
Location: /api/exports/exp_123
The client can then inspect progress without pinning application workers for minutes.
Do not trust URLs supplied by clients
Any feature that asks your server to fetch a remote URL introduces Server-Side Request Forgery risk.
Common examples include:
- webhook testers;
- image importers;
- URL preview generators;
- PDF generators;
- feed importers;
- callback validators;
- remote file ingestion.
A naive implementation:
var body = await httpClient.GetStringAsync(request.Url);
can potentially be coerced into talking to internal services, cloud metadata endpoints or loopback interfaces.
SSRF defense usually requires a combination of:
- strict scheme allowlists (
httpswhere possible); - destination validation;
- blocking loopback, link-local, private and internal ranges where not explicitly required;
- safe DNS resolution and re-resolution behaviour;
- redirect validation on every hop;
- outbound network segmentation;
- response-size limits;
- timeouts;
- content-type validation.
An application-level regex is not a complete SSRF defense.
Treat third-party API responses as untrusted input
Your code may trust Stripe, a CRM, a shipping provider or an internal microservice more than it trusts a browser. That trust can become dangerous.
The OWASP API Security Top 10 includes Unsafe Consumption of APIs for this reason.
Validate downstream responses before using them in security-sensitive decisions. Apply timeouts and size limits. Do not blindly follow URLs returned by another service. Do not deserialize polymorphic payloads into dangerous object graphs. Do not render third-party text as trusted HTML.
A dependency can be compromised, misconfigured or simply return unexpected data.
CORS is not API authentication
Cross-Origin Resource Sharing controls which browser origins may read responses using browser JavaScript. It does not prevent requests from curl, native apps, servers or attackers.
This configuration:
Access-Control-Allow-Origin: https://app.example.com
does not make an API private.
Likewise, allowing * is not automatically a vulnerability. The risk depends on credentials, data exposure and the intended public nature of the endpoint.
Design authentication and authorization independently of CORS.
Cookies introduce CSRF considerations
If your API uses browser cookies for authentication, the browser attaches them automatically. That changes the threat model compared with an API where JavaScript explicitly sends a bearer token.
Use appropriate cookie attributes:
Set-Cookie: session=...; Secure; HttpOnly; SameSite=Lax; Path=/
Then evaluate CSRF protection for state-changing operations based on your architecture, SameSite strategy and cross-origin requirements.
Do not disable CSRF protections merely because the endpoint returns JSON.
Webhook endpoints need their own trust model
A webhook is an inbound API controlled by another system.
Do not trust a request because it hits an obscure URL.
Prefer a provider-supported signature scheme and validate:
- signature;
- timestamp/freshness;
- expected signing secret/key;
- event identifier;
- replay behaviour.
Process events idempotently. Delivery systems retry. Duplicate webhook events are normal.
A useful processing model is:
receive
-> authenticate signature
-> persist event ID
-> reject/ignore duplicate
-> enqueue work
-> return quickly
Do not perform five minutes of downstream work before acknowledging the webhook.
Log security events without logging secrets
Useful API security telemetry includes:
authentication failures
authorization failures
rate-limit events
validation failures
unusual endpoint access
webhook signature failures
admin operations
privilege changes
idempotency conflicts
unexpected downstream destinations
Avoid logging:
access tokens
refresh tokens
passwords
API keys
session cookies
full payment-card data
sensitive request bodies
Structured logs should contain a correlation/request ID and enough context to investigate without turning the logging platform into a credential database.
Version and inventory every API you actually expose
A forgotten endpoint can be as dangerous as a vulnerable one.
Maintain an inventory of:
public APIs
partner APIs
internal APIs
admin APIs
webhooks
old versions
preview/beta versions
staging hosts
Retired versions should actually be retired. An old v1 endpoint left on an unadvertised hostname is still part of your attack surface.
Document owners and deprecation dates.
Test authorization as a matrix
The most valuable API security tests are often not happy-path unit tests.
For a resource such as an invoice, test at least:
owner can read own invoice
owner cannot read another tenant's invoice
support user can read according to support policy
read-only role cannot mutate
admin action requires admin capability
anonymous caller cannot read
suspended user cannot mutate
hidden properties never appear in output
protected properties cannot be mass-assigned
Then repeat the same thinking for list endpoints. A detail endpoint may be secure while /api/invoices accidentally returns every tenant’s records.
A practical production checklist
Before calling an API security-ready, verify that:
- authentication validates issuer, audience, signature and expiry;
- object authorization is enforced for every client-supplied resource reference;
- function authorization is explicit for privileged operations;
- request DTOs expose only writable fields;
- response DTOs expose only intended fields;
- tenant scope comes from trusted identity context where possible;
- pagination and expensive queries have hard limits;
- sensitive flows have abuse controls;
- outbound URL fetching is SSRF-hardened;
- third-party responses are validated;
- webhooks are authenticated and idempotent;
- secrets and tokens are not logged;
- obsolete API versions and debug endpoints are removed;
- authorization failure paths have automated tests.
Check what your public site is exposing
SiteTidy can inspect the delivered website for security, performance and configuration issues. Use API-specific tests alongside it for authorization and business-logic controls.
The principle to keep
API security becomes much easier to reason about when authorization, data exposure and resource consumption are treated as part of the contract rather than middleware added at the end.
Every request should be scoped. Every field should be intentional. Every expensive operation should have a limit. Every network boundary should assume the other side can eventually behave unexpectedly.
That is not paranoia. It is what lets an API stay reliable when it becomes important enough to attract both real traffic and hostile traffic.
