Advertisement
Advanced ASP.NET Core, CORS (Cross-Origin Resource Sharing)

How would you write an integration test verifying that a CORS policy correctly allows a specific origin and rejects an unauthorized one?

Short answer

Using WebApplicationFactory, send a request with an explicit Origin header set to both an allowed and a disallowed origin, then assert on the presence (or absence) of the Access-Control-Allow-Origin response header, verifying the actual CORS behavior end-to-end rather than just…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Using WebApplicationFactory, send a request with an explicit Origin header set to both an allowed and a disallowed origin, then assert on the presence (or absence) of the Access-Control-Allow-Origin response header, verifying the actual CORS behavior end-to-end rather than just trusting the policy configuration is correct by inspection alone.
[Fact]
public async Task Cors_AllowsConfiguredOrigin() {
    var client = _factory.CreateClient();
    var request = new HttpRequestMessage(HttpMethod.Get, "/api/products");
    request.Headers.Add("Origin", "https://app.mycompany.com");
    var response = await client.SendAsync(request);
    Assert.Equal("https://app.mycompany.com", response.Headers.GetValues("Access-Control-Allow-Origin").First());
}
Real-world example
A CI pipeline runs automated CORS policy tests confirming the production allowlist correctly permits the actual deployed frontend origin and rejects a deliberately unauthorized test origin, catching configuration regressions before they reach production.
Likely follow-ups
  • How would you test the preflight OPTIONS request behavior specifically, not just the actual GET/POST response?
  • What's the risk of only manually verifying CORS configuration instead of automated tests?
Related topics