Web & DataComplete guide

API Security & OWASP

API security applies identity, authorization, input boundaries, abuse controls, secure configuration, and continuous verification to every exposed operation and object.

Overview

The OWASP API Security Top 10 highlights recurring risks including broken object-level authorization, broken authentication, broken object-property authorization, unrestricted resource consumption, broken function authorization, unrestricted access to sensitive business flows, server-side request forgery, security misconfiguration, poor API inventory, and unsafe consumption of upstream APIs. ASP.NET Core supplies authentication, policy authorization, request limits, rate limiting, Problem Details, data protection, output controls, and test hosting, but controls only work when attached to explicit assets, actors, tenants, resources, operations, and trust boundaries. Production API security is continuous: inventory every host and version, validate and minimize input and output contracts, authorize each function and loaded object, bound memory, CPU, time, concurrency, pages, uploads, and downstream calls, restrict outbound destinations, protect secrets, patch dependencies, observe abuse without logging sensitive data, and retire obsolete surfaces. The OWASP list is a prioritization lens rather than a checklist that replaces threat modeling, abuse-case analysis, secure design review, negative tests, dependency auditing, and deployed-environment verification.

What you will learn

  • Map OWASP API risks to concrete ASP.NET Core controls and tests.
  • Threat-model assets, actors, tenants, trust boundaries, entry points, and abuse cases.
  • Prevent object, property, and function authorization failures.
  • Bound resource consumption and sensitive business workflows beyond one global rate limit.
  • Prevent SSRF and unsafe upstream consumption through destination, protocol, response, and timeout controls.
  • Maintain an accurate API inventory and retire obsolete versions safely.
  • Verify controls continuously through negative tests, telemetry, dependency audit, and deployment review.

Prerequisites

  • HTTP APIs, JSON contracts, authentication, authorization, and status codes.
  • ASP.NET Core middleware, routing, dependency injection, and integration testing.
  • Basic threat-model concepts such as asset, actor, trust boundary, attack surface, and abuse case.
  • A .NET 10 SDK to run the dedicated secure order API.

When to use API Security & OWASP

Good fit

  • Use the OWASP API Security Top 10 to structure awareness, design review, testing, and backlog prioritization.
  • Use system-specific threat modeling to decide which controls and evidence each endpoint needs.
  • Use defense in depth across edge, application, data, dependency, identity, delivery, and monitoring layers.

Choose another approach when

  • Do not claim an API is secure because a scanner or Top 10 checklist passed.
  • Do not treat authentication, TLS, CORS, or an API gateway as a replacement for object and function authorization.
  • Do not use rate limits as the only defense for costly operations or sensitive business workflows.
  • Do not consume arbitrary client-selected URLs or trust upstream responses because the dependency is internal.

Key concepts

Object-level authorization

Every request for a specific record must verify the caller can access that object; a valid token alone does not prevent identifier-based data exposure.

Abuse and resource controls

Rate limits, request-size limits, pagination, timeouts, quotas, and workflow-specific rules protect compute and sensitive business flows.

Input and output boundaries

Purpose-built request and response models, validation, allowlists, and minimal serialization reduce mass assignment and excessive data exposure.

Inventory and dependencies

Teams must know which API versions and hosts exist, patch them, retire stale endpoints, and treat upstream API responses as untrusted input.

Object-property authorization

Allowlisted request DTOs prevent mass assignment, and minimal response DTOs prevent excessive exposure of internal or caller-forbidden properties.

Function authorization

Every operation enforces server-side policy; a role, route name, HTTP method, or hidden UI is not sufficient permission by itself.

Sensitive business flows

Purchasing, booking, signup, recovery, and other valuable workflows need actor-aware quotas, sequencing, idempotency, fraud controls, and monitoring.

SSRF and unsafe consumption

Outbound calls require allowlisted destinations and schemes, DNS and redirect awareness, timeouts, size bounds, response validation, and restricted egress.

Architecture

Traffic passes through trusted edge controls, strict protocol and resource bounds, validated identity, function and resource authorization, allowlisted contracts, domain workflow controls, protected data access, and constrained upstream clients while correlated telemetry records security-relevant outcomes.

Client + edge
Protocol limits
Authentication
Function policy
Resource authorization
Workflow rules
Data + upstream clients
Security telemetry

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated order API converts common risks into executable boundaries: tenant and subject authorization, bounded inputs, minimal response DTOs, request limits, rate limiting, an outbound destination allowlist, safe errors, and negative integration tests.

  1. 01
    Inventory the surface

    Record hosts, routes, versions, owners, data classifications, clients, dependencies, and retirement dates.

  2. 02
    Threat-model operations

    Identify assets, actors, trust boundaries, object identifiers, privileged functions, costly work, and sensitive workflows.

  3. 03
    Constrain contracts

    Use allowlisted request and response DTOs, validate shape and semantics, and cap bodies, collections, pages, and files.

  4. 04
    Authorize functions and objects

    Require server policy, load inside the tenant boundary, and authorize subject, resource, operation, and state.

  5. 05
    Bound resource use

    Apply actor-aware quotas, concurrency limits, timeouts, cancellation, idempotency, and workflow controls.

  6. 06
    Constrain dependencies

    Allowlist outbound hosts and schemes, restrict redirects and egress, validate responses, and bound response size and duration.

  7. 07
    Test and observe abuse

    Automate negative cases, audit dependencies and configuration, monitor denied and anomalous behavior, and rehearse response.

Code example

The endpoint requires authentication and rate limiting, loads the target resource, then performs resource-aware authorization before returning a minimal response.

OrderEndpoints.cs
app.MapGet("/api/orders/{id:guid}", async (
    Guid id,
    ClaimsPrincipal user,
    IOrderRepository orders,
    IAuthorizationService authorization,
    CancellationToken ct) =>
{
    var order = await orders.FindAsync(id, ct);
    if (order is null)
        return Results.NotFound();

    var decision = await authorization.AuthorizeAsync(
        user, order, "CanReadOrder");

    return decision.Succeeded
        ? Results.Ok(new OrderResponse(order.Id, order.Status))
        : Results.Forbid();
})
.RequireAuthorization()
.RequireRateLimiting("authenticated-api");

Testing strategy

Negative tests are executable threat-model evidence, not optional edge cases.

  • Test anonymous, invalid identity, wrong role, wrong tenant, non-owner, and forbidden function access.
  • Test over-posted properties and assert internal or unauthorized fields never appear in responses.
  • Test oversized bodies, collections, page sizes, repeated requests, concurrent requests, timeouts, and cancellation.
  • Test metadata, loopback, private-network, alternate-scheme, redirect, DNS, and oversized upstream-response SSRF cases.
  • Run dependency, secret, static, dynamic, and configuration scans, then verify findings against the deployed environment.

Security considerations

API security combines prevention, detection, recovery, and continuous inventory across every trust boundary.

  • Authenticate through trusted schemes and authorize every function, tenant, object, and sensitive property.
  • Validate, normalize, and allowlist input while returning only purpose-built response contracts.
  • Use least privilege for databases, queues, storage, service identities, and outbound network access.
  • Protect credentials and keys, patch dependencies, harden production configuration, and remove debug endpoints.
  • Log security outcomes with correlation and redaction, alert on abuse patterns, and retain evidence according to policy.

Performance and scalability

Resource bounds are both capacity engineering and security controls.

  • Cap request and response bodies, uploads, decompression, JSON depth, collection length, and page size before large allocation.
  • Use per-actor and per-workflow quotas plus global safeguards; include concurrency and cost, not only request count.
  • Propagate cancellation and set timeouts on databases and outbound calls.
  • Reject invalid or unauthorized work before expensive queries, file processing, model calls, or downstream effects.
  • Load-test abusive patterns and monitor CPU, memory, queue depth, rejection rate, and dependency saturation.

Deployment and operations

Security controls must survive the real proxy, network, identity, configuration, and release pipeline.

  • Apply trusted forwarded-header, TLS, host, CORS, request-limit, and security-header configuration at the real edge path.
  • Run as least privilege, restrict egress, separate environments, and keep secrets in managed stores.
  • Generate and review an API inventory and dependency inventory for every release.
  • Deploy compatible contract changes, retire old versions on schedule, and remove abandoned hosts and credentials.
  • Smoke-test negative cases, telemetry, alerting, rollback, and incident procedures after deployment.

Common problems and fixes

Changing an identifier returns another user's data.

Likely cause: Object-level authorization is absent or occurs after response mapping.

Fix: Scope loading to tenant and subject, authorize the resource, and add cross-owner tests.

Clients can set privileged fields.

Likely cause: Persistence entities or broad models are bound directly.

Fix: Use allowlisted request DTOs and server-owned values.

One request exhausts memory or CPU.

Likely cause: Bodies, collections, decompression, queries, or downstream work are unbounded.

Fix: Reject early with explicit size, complexity, time, concurrency, and cost limits.

An outbound URL reaches internal metadata.

Likely cause: Client-controlled destinations, redirects, DNS, or egress are unrestricted.

Fix: Use fixed or allowlisted destinations, HTTPS, redirect controls, IP validation, and network egress policy.

A retired version remains reachable.

Likely cause: Inventory and decommission ownership are incomplete.

Fix: Discover hosts and gateways, assign owners and retirement dates, remove routes and credentials, and monitor for traffic.

Security logs expose tokens or personal data.

Likely cause: Headers, bodies, or claims are logged without classification and redaction.

Fix: Use allowlisted structured fields, centralized redaction, access controls, and retention rules.

Best practices

  • Threat-model assets, actors, trust boundaries, and abuse cases and convert them into tests.
  • Authorize every function, tenant, and requested resource on the server.
  • Use allowlisted request and response contracts instead of persistence entities.
  • Bound bodies, pages, queries, concurrency, duration, retries, and outbound destinations.
  • Protect sensitive business flows with actor-aware quotas, sequencing, idempotency, and monitoring.
  • Treat upstream responses and internal networks as untrusted and constrain egress.
  • Maintain and retire an owned API inventory and patch all dependencies.
  • Test controls in the deployed environment and monitor security outcomes without leaking data.

Production checklist

  • Every API host, route, version, owner, data class, client, dependency, and retirement date is inventoried.
  • Threat models cover objects, functions, properties, business flows, resource consumption, SSRF, and dependencies.
  • Authentication and tenant-aware object and function authorization have negative tests.
  • Request, response, upload, page, concurrency, duration, retry, and downstream costs are bounded.
  • Outbound destinations, schemes, redirects, DNS resolution, response size, and egress are constrained.
  • Secrets, packages, images, configuration, and infrastructure are scanned and patched.
  • Errors and telemetry are correlated and redacted; abuse alerts and incident runbooks are tested.
  • The real deployed edge path, old-version retirement, rollback, and recovery are verified.

Common interview questions

What is broken object-level authorization (BOLA)?

It occurs when an API accepts an object identifier but does not verify that the authenticated caller is allowed to act on that specific object, allowing access by changing identifiers.

Why is rate limiting not a complete authorization control?

Rate limiting controls volume, not permission. A caller below the limit can still access the wrong tenant, object, function, or business workflow unless authorization is enforced separately.

How should an API consume an upstream API safely?

Authenticate the dependency, restrict destinations, set timeouts and size limits, validate responses, avoid blindly following redirects, and treat returned data as untrusted.

What is broken object-property authorization?

It occurs when callers can set properties they should not control or receive properties they should not see; explicit request and response DTOs reduce both risks.

Why is an API inventory a security control?

Unknown or obsolete hosts and versions escape patching, monitoring, ownership, and retirement, leaving unmanaged attack surface.

How do you defend against SSRF?

Avoid arbitrary destinations; allowlist schemes and hosts, control redirects and DNS/IP resolution, restrict egress, set time and size limits, and validate responses.

What is sensitive business-flow abuse?

A legitimate operation such as booking or recovery is automated or repeated for harmful advantage, requiring workflow-specific limits beyond technical authentication.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

API Security & OWASP Orders

A .NET 10 API demonstrating tenant and object authorization, bounded resources, minimal contracts, SSRF destination controls, security headers, safe errors, and OWASP-aligned negative tests.

ASP.NET Core 10OWASP API SecurityRate LimitingxUnit
dedicated-samplebolaresource-boundsssrfnegative-testing
Run
dotnet run --project src/ApiSecurityOwaspOrders
Test
dotnet test ApiSecurityOwaspOrders.slnx