OWASP API Security Top 10 Review of a .NET API
On this page
Learning Objective
Walk through the OWASP API Security Top 10 2023 against a real codebase, produce a findings table with fixes and regression tests, apply the two categories not yet covered in this course, server-side request forgery and abuse of business flows, and set up automated checks so the review keeps paying off.
Concept Explanation
The OWASP API Security Top 10 is a ranked list of the most critical risks facing APIs, and the 2023 edition is a compact syllabus for everything this phase covered. API1 is Broken Object Level Authorization, API2 Broken Authentication, API3 Broken Object Property Level Authorization, API4 Unrestricted Resource Consumption, API5 Broken Function Level Authorization, API6 Unrestricted Access to Sensitive Business Flows, API7 Server Side Request Forgery, API8 Security Misconfiguration, API9 Improper Inventory Management, and API10 Unsafe Consumption of APIs. Reviewing your own service against that list is one of the highest-return security activities a small team can do, and this project makes it concrete.
Run the review as an exercise with evidence. For each category, state where in the code the risk would appear, try to break it with a test or a manual request, record whether it holds, and where it does not, fix it and leave a regression test behind. Several categories map directly onto earlier lessons: object and property authorization to Days 23 and 47, authentication to Days 42 through 46, resource consumption to Days 24, 28, and 29, function-level authorization to Day 47, misconfiguration to Days 11, 19, and 48, and inventory to Days 18 and 25. Two are new here. Unrestricted access to sensitive business flows is abuse of legitimate functionality at scale, such as bulk-creating accounts, scraping, or exhausting a coupon or invitation quota; the defense combines rate limits with business-aware limits and detection. Server-side request forgery, SSRF, arises when the server fetches a URL supplied by a user, such as a webhook or an avatar link, and the attacker points it at internal resources.
SSRF deserves attention because cloud environments make it especially dangerous. From inside a virtual machine or container, a request to a link-local metadata address can return the platform's credentials, so an SSRF flaw can hand an attacker the identity of your server. The defense is layered: avoid fetching user-supplied URLs at all where possible, otherwise allow only https URLs to an allowlist of hosts, resolve the name and reject private, loopback, and link-local addresses, do not follow redirects blindly because they can bounce to internal addresses, apply short timeouts and response size limits, and run the fetcher in a network segment with no access to internal services. Managed identities with narrow permissions and metadata endpoints that require a special header reduce the damage if a request does get through.
Finish by automating what you can. Dependency scanning, static analysis with the built-in .NET analyzers, secret scanning, and a dynamic baseline scan with OWASP ZAP in the pipeline catch regressions and the easy findings, freeing human review for design flaws. Treat the review's findings table and its tests as living documents: when a new endpoint is added, walk the ten categories for it. The point is a habit, not a report, and the habit is what separates teams that are breached from teams that catch problems in review.
| Category | Question to ask | Where to look |
|---|---|---|
| API1 Object level authorization | Can I fetch or change another user's object by changing an id? | Every endpoint with an id parameter |
| API2 Broken authentication | Are tokens validated, sessions protected, login throttled? | Auth setup, login endpoints |
| API3 Property level authorization | Do responses or requests expose or accept too many fields? | DTOs, binding, unmapped members |
| API4 Resource consumption | Are page sizes, body sizes, rates and timeouts bounded? | List endpoints, uploads, expensive queries |
| API5 Function level authorization | Can a normal user call admin operations? | Admin routes, HTTP method variations |
| API6 Business flow abuse | Can a legitimate flow be automated to cause harm? | Invitations, signup, exports, coupons |
| API7 SSRF | Does the server fetch a user-supplied URL? | Webhooks, imports, avatars, previews |
| API8 Misconfiguration | Headers, CORS, error detail, defaults, debug endpoints? | Pipeline, hosting settings |
| API9 Inventory | Are old versions, docs and test hosts still exposed? | Versioning, OpenAPI, environments |
| API10 Unsafe consumption | Do we trust data from third-party APIs? | Outbound clients and their responses |
Worked Example: A Findings Table, an SSRF-Safe Fetcher and Pipeline Checks
The table shows what a review of the Notes API might record. The code implements the SSRF defense for a webhook feature, and the pipeline excerpt automates the baseline checks.
Finding Category Evidence Fix Regression test
F1 API1 GET /api/notes/{id} returned another user's note Filter by OwnerId in the query Users_cannot_read_each_others_notes
F2 API3 PUT accepted "ownerId" in the body and changed owner Request type without OwnerId; disallow Unknown_member_is_rejected
unmapped members
F3 API4 GET /api/notes?pageSize=100000 returned everything Clamp to 100 PageSize_is_capped
F4 API5 DELETE /api/admin/users worked with a member token Admin group policy Access_matrix row: member on admin
F5 API8 Error responses included stack traces in Staging Exception handler on all environments Errors_never_contain_stack_frames
F6 API9 /openapi/v1.json and Scalar UI served in Production Register only when not Production Docs_not_exposed_in_production
F7 API6 Invitation endpoint sends unlimited emails per user Per-user daily quota + rate limit Invitation_quota_enforced
F8 API7 Webhook URL fetched without validation Validated fetcher below Webhook_rejects_internal_addressespublic sealed class SafeWebhookClient(IHttpClientFactory factory)
{
public async Task<bool> IsAllowedAsync(Uri uri, CancellationToken ct)
{
if (uri.Scheme != Uri.UriSchemeHttps || uri.IsLoopback || uri.Port is not 443) return false; // https on 443 only
var addresses = await Dns.GetHostAddressesAsync(uri.DnsSafeHost, ct);
return addresses.Length > 0 && addresses.All(IsPublic); // every resolved address must be public
}
static bool IsPublic(IPAddress ip)
{
if (IPAddress.IsLoopback(ip) || ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6UniqueLocal) return false;
var b = ip.MapToIPv4().GetAddressBytes();
return !(b[0] == 10 || // 10.0.0.0/8
(b[0] == 172 && b[1] is >= 16 and <= 31) || // 172.16.0.0/12
(b[0] == 192 && b[1] == 168) || // 192.168.0.0/16
(b[0] == 169 && b[1] == 254) || // link-local, includes the cloud metadata address
b[0] == 0 || b[0] >= 224); // unspecified, multicast, reserved
}
public async Task SendAsync(Uri uri, string json, CancellationToken ct)
{
if (!await IsAllowedAsync(uri, ct)) throw new WebhookRejectedException();
var client = factory.CreateClient("webhooks"); // AllowAutoRedirect = false, Timeout = 5 seconds
using var req = new HttpRequestMessage(HttpMethod.Post, uri) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
using var res = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct);
// Never return the response body to the caller: that would turn blind SSRF into full SSRF.
}
}
// Note: resolve-then-connect can be raced by DNS rebinding. For strong protection, pin the resolved IP
// in a SocketsHttpHandler.ConnectCallback that re-checks the address at connection time.# .github/workflows/security.yml (excerpt): automated checks on every pull request
- run: dotnet list package --vulnerable --include-transitive | tee vuln.txt
- run: "! grep -q 'has the following vulnerable packages' vuln.txt"
- uses: gitleaks/gitleaks-action@v2 # secret scanning
- run: dotnet build -warnaserror # .NET analyzers as errors, including EF1002 raw SQL
- name: OWASP ZAP baseline scan against the staging deployment
uses: zaproxy/action-baseline@v0.12.0
with: { target: 'https://staging.example.com' }Finding F2 shows the value of testing beyond the obvious: the endpoint had a request type, but the deserializer was ignoring unknown members, so the ownerId in the body was silently dropped rather than rejected. Rejecting unknown members turns a silent attack attempt into a visible 400 and a log entry to alert on.
Real-World Examples
- In 2019, Capital One suffered a breach affecting roughly 100 million people in the United States, in which an attacker exploited a server-side request forgery weakness in a misconfigured web application firewall to reach the cloud metadata service and obtain temporary credentials for an over-permissioned role, which were then used to read data from storage buckets. It is the standard case study for SSRF in the cloud, and the reason later metadata service versions require session tokens or special headers.
- The OWASP API Security Top 10 was first published in 2019 and updated in 2023, adding categories such as unrestricted access to sensitive business flows, server side request forgery, and unsafe consumption of APIs, based on data from real incidents and contributions from practitioners. It is widely used as a baseline in penetration test scopes and compliance mappings, so a team that has walked it themselves is far better prepared for an external assessment.
Review Questions & Answers
The server can reach internal network locations the attacker cannot, including the instance metadata service that hands out temporary credentials for the machine's role. A single unvalidated URL fetch can therefore turn into theft of cloud credentials and access to storage and databases, as happened in the 2019 Capital One breach. Layered URL validation, no redirects, and minimal role permissions reduce the risk.
A hostname that looks harmless can resolve to a private or link-local address, either deliberately by the attacker or via DNS records under their control. Checking only the string misses that. Resolving and validating every address, and ideally pinning the connection to the validated address, closes the gap, since attackers can also try DNS rebinding tricks.
It is the automated abuse of legitimate functionality, such as bulk account creation, mass invitations, or scraping, where each request looks valid on its own. Simple per-second rate limits may not stop it, so the defense is business-aware: quotas per user per day, friction on high-value actions, anomaly detection, and monitoring of how the flow is used, not merely how fast.
Fixes without tests tend to regress silently when code is refactored or new endpoints are added. A test that asserts another user's note returns 404, or that an internal webhook address is rejected, keeps the protection permanently verified by the build. The tests also document the threat model as executable checks for future developers.