Dynamic CORS in ASP.NET Core for Multi-Tenant Apps
In modern web development, Cross-Origin Resource Sharing (CORS) is a fundamental security mechanism. For standard, single-client applications, configuring a CORS policy in ASP.NET Core is straightforward: you define a set of allowed origins in your Program.cs. But what happens when you’re building a multi-tenant application where each tenant needs a different set of allowed origins?
A static, hardcoded list of origins quickly becomes a bottleneck. Adding a new tenant or updating a tenant’s domain would require a code change and a redeployment. This is not scalable or secure. The solution is to create a dynamic, per-tenant CORS policy that resolves the correct origins at runtime.
In this post, we’ll build a custom ASP.NET Core middleware to achieve exactly that. We’ll create a flexible system that looks up a tenant’s specific CORS configuration on the fly for each incoming request.
The Problem with Static CORS in Multi-Tenant Architectures
Let’s quickly review the standard approach. In a typical Program.cs, you might see this:
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("[https://client-app-one.com](https://client-app-one.com)", "[https://client-app-two.com](https://client-app-two.com)")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// ... in the pipeline configuration
app.UseCors();
This works perfectly for a predictable …
...