Testing ASP.NET Core Authentication and Authorization
On this page
Learning Objective
Build automated security tests that enumerate every endpoint to prove it requires authorization, run access matrices and cross-tenant probes, verify security headers, CORS and rate limits, and use API fuzzing tools to find what hand-written tests miss.
Concept Explanation
Security controls fail silently: a missing authorization check produces no error, and the endpoint works perfectly for everyone. That is why they need tests written specifically to look for absence. The most valuable single test in an API project is one that enumerates every endpoint the application exposes and asserts that each is either protected or on an explicit allowlist of public routes. ASP.NET Core exposes the endpoint data sources, so a test can list every route, inspect its metadata for authorization requirements, and fail if a new endpoint has neither. Adding an endpoint then forces a conscious decision about whether it is public, exactly the property you want.
Beyond the presence of a requirement you must test that it works, which is the access matrix from Day 47 executed against real requests: each role and caller type against each operation, with the negative cells as important as the positive ones. Extend it to cross-tenant and cross-user probes that take every endpoint accepting an identifier and call it with a resource belonging to someone else. With the OpenAPI document available, this can be automated: for each operation with a path parameter, create a resource as user A, then attempt to read, modify, and delete it as user B, expecting 404 in every case. Broken object level authorization is the top API risk, and this loop finds it systematically instead of hoping developers remembered.
Test the surrounding protections as well. Assert that responses carry the expected security headers, that CORS answers with the allowed origin for your site and nothing for a fabricated one, that the login endpoint returns 429 after too many attempts, that tokens with a missing audience, wrong issuer, expired lifetime, or algorithm none are rejected, that cookies are set with HttpOnly, Secure, and SameSite attributes, and that error responses never contain stack traces. Each of these is a short test, and together they turn a written security policy into something the build enforces. Add mass-assignment probes, sending extra properties such as isAdmin or ownerId in request bodies and asserting they are rejected or ignored.
Automation extends your reach beyond the cases you thought of. Schemathesis, an open source tool, reads an OpenAPI document and generates a large variety of valid and invalid requests for each operation, checking for server errors, schema violations, and unexpected behavior. Microsoft Research's RESTler is a stateful fuzzer that learns dependencies between requests, for example that a created resource's id feeds a later call. OWASP ZAP can run an active scan against a test deployment. Run these against a test environment with test data, never production, and treat every 500 response they find as a bug worth understanding, because unhandled server errors on malformed input are often the first sign of a deeper weakness.
| Test | What it proves | How |
|---|---|---|
| Every endpoint is protected or allowlisted | No accidental public endpoint | Enumerate EndpointDataSource metadata |
| Role by operation matrix | Correct access for each caller type | Table-driven theory against real requests |
| Cross-user and cross-tenant probes | No broken object level authorization | Create as A, access as B for every id route |
| Token rejection cases | Validation of issuer, audience, expiry, algorithm | Hostile tokens built with a throwaway key |
| Headers, CORS, cookies, rate limits | Baseline hardening in place | Assertions on real responses |
| Fuzzing from OpenAPI | Unexpected inputs do not cause 500 errors | Schemathesis, RESTler, ZAP against a test host |
Worked Example: Enumerating Endpoints, Probing Ownership and Checking Hardening
The first test inspects endpoint metadata. The second probes cross-user access for every identifier route using the OpenAPI document. The rest verify headers, CORS, cookies, and the login limit.
[Collection("api")]
public class SecurityBaselineTests(ApiFactory factory)
{
// Public endpoints must be listed on purpose. Everything else must require authorization.
private static readonly HashSet<string> Public =
[
"GET /health", "GET /api/catalog", "POST /auth/login", "POST /csp-reports", "GET /bff/user",
];
[Fact]
public async Task Every_endpoint_requires_authorization_or_is_explicitly_public()
{
// The fallback policy from Day 12 protects endpoints that carry no explicit metadata.
var hasFallback = await factory.Services.GetRequiredService<IAuthorizationPolicyProvider>().GetFallbackPolicyAsync() is not null;
var sources = factory.Services.GetServices<EndpointDataSource>();
var unprotected = new List<string>();
foreach (var endpoint in sources.SelectMany(s => s.Endpoints).OfType<RouteEndpoint>())
{
var methods = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods ?? ["ANY"];
var requiresAuth = endpoint.Metadata.GetMetadata<IAuthorizeData>() is not null; // fallback policy also counts
var allowsAnonymous = endpoint.Metadata.GetMetadata<IAllowAnonymous>() is not null;
foreach (var m in methods)
{
var key = $"{m} /{endpoint.RoutePattern.RawText?.TrimStart('/')}";
if (allowsAnonymous && !Public.Contains(key)) unprotected.Add($"{key} is anonymous but not on the allowlist");
if (!requiresAuth && !allowsAnonymous && !hasFallback) unprotected.Add($"{key} has no authorization");
}
}
Assert.Empty(unprotected);
}
[Fact]
public async Task No_endpoint_lets_user_B_reach_user_As_objects()
{
var a = factory.CreateClient().AsUser("alice"); var b = factory.CreateClient().AsUser("bob");
var seeded = await new Seeder(a).CreateOneOfEachAsync(); // returns { "/api/notes/{id}": "/api/notes/17", ... }
foreach (var (template, concrete) in seeded)
{
Assert.Equal(HttpStatusCode.NotFound, (await b.GetAsync(concrete)).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await b.SendAsync(new(HttpMethod.Delete, concrete))).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await b.PatchAsJsonAsync(concrete, new { title = "hijacked" })).StatusCode);
}
}
[Fact]
public async Task Extra_properties_in_a_body_are_rejected_not_assigned()
{
var res = await factory.CreateClient().AsUser("alice")
.PostAsJsonAsync("/api/notes", new { title = "x", ownerId = "bob", isAdmin = true });
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode); // unmapped members are disallowed
}
[Fact]
public async Task Responses_carry_security_headers_and_no_server_banner()
{
var res = await factory.CreateClient().GetAsync("/health");
Assert.Equal("nosniff", res.Headers.GetValues("X-Content-Type-Options").Single());
Assert.Contains("frame-ancestors 'none'", res.Headers.GetValues("Content-Security-Policy").Single());
Assert.False(res.Headers.Contains("Server"));
Assert.False(res.Headers.Contains("X-Powered-By"));
}
[Theory]
[InlineData("https://app.example.com", true)]
[InlineData("https://evil.example", false)]
[InlineData("null", false)]
public async Task Cors_allows_only_listed_origins(string origin, bool allowed)
{
var req = new HttpRequestMessage(HttpMethod.Options, "/api/notes");
req.Headers.Add("Origin", origin); req.Headers.Add("Access-Control-Request-Method", "POST");
var res = await factory.CreateClient().SendAsync(req);
Assert.Equal(allowed, res.Headers.Contains("Access-Control-Allow-Origin"));
}
[Fact]
public async Task The_login_endpoint_is_rate_limited()
{
var client = factory.CreateClient();
HttpStatusCode last = 0;
for (var i = 0; i < 8; i++)
last = (await client.PostAsJsonAsync("/auth/login", new { email = "a@b.com", password = "wrong" })).StatusCode;
Assert.Equal(HttpStatusCode.TooManyRequests, last);
}
[Fact]
public async Task Errors_never_expose_stack_traces()
{
var res = await factory.CreateClient().AsUser("alice").GetAsync("/api/test-support/throw"); // endpoint mapped only in Testing
var body = await res.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.InternalServerError, res.StatusCode);
Assert.DoesNotMatch(@"\bat [A-Za-z_.]+\(", body);
Assert.DoesNotContain("Exception", body);
}
}# Fuzzing against a TEST deployment seeded with test data. Never point these tools at production.
pip install schemathesis
schemathesis run https://staging.example.com/openapi/v1.json \
--header "Authorization: Bearer $TEST_TOKEN" \
--checks all --max-examples 200 --workers 4
# Any 5xx response is a finding: malformed input must produce a 4xx, never an unhandled error.
# OWASP ZAP baseline (passive) or full (active) scan from a container:
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.com -r zap-report.htmlKeep the allowlist of public endpoints short and reviewed. When a pull request adds a line to it, that is exactly the moment a reviewer should ask whether the endpoint really must be public.
Real-World Examples
- Schemathesis is an open source property-based testing tool for APIs that generates requests from OpenAPI and GraphQL schemas and reports crashes, schema violations, and other anomalies. It has found server errors in many well-known public APIs, and teams run it in CI against test deployments to catch unhandled input cases that unit and integration tests seldom cover.
- RESTler, released by Microsoft Research in 2019, is the first stateful REST API fuzzing tool: it analyzes the OpenAPI specification to infer producer and consumer dependencies between requests, then chains calls so later requests use resources created by earlier ones. It has been used to find bugs in cloud services, illustrating why a fuzzer that understands API workflows reaches deeper than random inputs.
Review Questions & Answers
Missing authorization produces no visible failure, so it goes unnoticed until exploited. A test that inspects every endpoint's metadata fails the build when any endpoint is neither protected nor on the reviewed public allowlist, forcing a conscious decision whenever a route is added and catching the forgotten check before release.
It systematically tries every identifier-taking endpoint with another user's resource, including endpoints that developers did not think to include in the matrix, and covers reads, updates, and deletes. Because it is driven by the API description, new endpoints are covered automatically, closing gaps left by human omission.
Malformed or unexpected input should always produce a controlled 4xx response. A 500 indicates an unhandled condition, which may cause crashes or resource problems, may leak information in some configurations, and often points to a deeper validation or logic weakness that a more targeted attack could exploit.
They send large volumes of unusual requests, including ones that create, modify, or delete data and can trigger errors, load, and alerts. Running them on production risks corrupting real data, degrading service for users, and setting off incident responses. A dedicated test deployment with synthetic data gives the same findings safely.