skip to content

In an ASP.NET Core CORS policy, how do you safely allow credentialed calls from every tenant storefront's own subdomain to the coffee-subscription API?

level: seniorimportance: should knowfreq 27%

answer

  1. a list you cannot write out
  2. SetIsOriginAllowedToAllowWildcardSubdomains with *.
  3. SetIsOriginAllowed(Func<string, bool>)
  4. custom predicate adds Vary: Origin
  5. ICorsPolicyProvider for async lookups

basics

~10 s

Use WithOrigins("https://*.shops.coffee.example") with SetIsOriginAllowedToAllowWildcardSubdomains, or SetIsOriginAllowed with a predicate that checks the parsed origin against your tenant list, plus AllowCredentials. Never approve every origin.

solid answer

~40 s

ASP.NET Core gives three tools. `SetIsOriginAllowedToAllowWildcardSubdomains()` with `WithOrigins("https://*.shops.coffee.example")` accepts any host ending in `.shops.coffee.example` with the same scheme and port. `SetIsOriginAllowed(Func<string, bool>)` replaces the exact match with your own synchronous check, for example parsing the origin and looking the host up in an in-memory tenant registry. For a lookup that must be asynchronous, implement `ICorsPolicyProvider`, whose `GetPolicyAsync` returns a `CorsPolicy` per request. With either custom predicate the middleware adds `Vary: Origin` for you; a per-request policy that lists only the caller's origin does not, so add it yourself. `AllowCredentials()` is accepted with any predicate, so a predicate that approves everything reopens the wildcard-with-cookies hole the builder otherwise forbids.

code

csharp · 12 lines
csharp
builder.Services.AddSingleton<TenantRegistry>();
builder.Services.AddCors();
builder.Services.AddOptions<CorsOptions>()
    .Configure<TenantRegistry>((options, tenants) =>
        options.AddPolicy("TenantStorefronts", policy => policy
            .SetIsOriginAllowed(origin =>
                Uri.TryCreate(origin, UriKind.Absolute, out var uri)
                && uri.Scheme == Uri.UriSchemeHttps
                && tenants.IsActiveStorefrontHost(uri.Host))
            .AllowAnyHeader()
            .WithMethods("GET", "POST", "DELETE")
            .AllowCredentials()));

go deeper

for a junior

Know that WithOrigins needs exact origins and that ASP.NET Core offers SetIsOriginAllowed and wildcard subdomains when the list is dynamic.

for a middle

Explain how the wildcard subdomain check matches host, scheme and port, and why a custom predicate makes the middleware add Vary: Origin.

for a senior

Build a predicate on parsed hosts from a cached registry, separate credentialed and public policies, and catch suffix checks and approve-all predicates in review.

for a principal

Decide between per-tenant subdomains with dynamic CORS and a single storefront origin per tenant routed through a proxy, weighing governance against operational cost.

## The problem with a fixed list `WithOrigins` takes exact strings. A multi-tenant storefront at `https://{tenant}.shops.coffee.example` has as many origins as tenants, and the list changes whenever a tenant signs up. ASP.NET Core has three ways to express that without giving up the allow-list. ## Option 1: wildcard subdomains ```csharp policy.WithOrigins("https://*.shops.coffee.example") .SetIsOriginAllowedToAllowWildcardSubdomains(); ``` - The `*.` must be in the origin string; the call then sets `IsOriginAllowed` to a check that first tries an exact match and then, for entries containing `://*.`, accepts an origin whose **host ends with `.shops.coffee.example`**, whose **scheme** is the same and whose **port** is the same. - The bare `https://shops.coffee.example` is **not** matched unless listed separately, and deeper names such as `a.b.shops.coffee.example` are matched. - It is cheap and static, but it trusts **every** subdomain, including ones a tenant or a forgotten DNS record controls. ## Option 2: your own predicate `SetIsOriginAllowed(Func<string, bool>)` replaces the default exact match. The predicate receives the raw `Origin` value and must return quickly, because it runs on every cross-origin request and it is synchronous. - Parse with `Uri.TryCreate`, require `https`, and compare the host against a **known set**, not a suffix you built with `EndsWith`. - Keep the tenant set in memory (a singleton refreshed in the background), not in a database call per request. - To reach a service from the policy, configure `CorsOptions` through `builder.Services.AddOptions<CorsOptions>().Configure<TenantRegistry>((options, tenants) => ...)`, since the plain `AddCors(options => ...)` delegate has no access to DI. ## Option 3: `ICorsPolicyProvider` `ICorsPolicyProvider.GetPolicyAsync(HttpContext, string? policyName)` returns `Task<CorsPolicy?>`. `AddCors` registers `DefaultCorsPolicyProvider` with `TryAdd`, so registering your own implementation replaces it. A provider can await a tenant lookup and build a policy per request; returning `null` means "no policy", and the middleware sends no CORS headers. ## Headers the middleware adds, and the one it does not | Configuration | `Vary: Origin` added? | |---|---| | one `WithOrigins` entry, default matching | no | | two or more `WithOrigins` entries | yes | | `SetIsOriginAllowed` or wildcard subdomains | yes | | provider building a policy with only the caller's origin | **no**, add it yourself | `Vary: Origin` tells caches that the response differs per `Origin`. Without it, a cached response carrying tenant A's `Access-Control-Allow-Origin` can be replayed to tenant B, which then fails, or to an intermediary that mixes responses up. ## Where `AllowCredentials` stops protecting you `CorsPolicyBuilder.Build()` refuses only `AllowAnyOrigin()` with `AllowCredentials()`. Any predicate is accepted with credentials, so: 1. `SetIsOriginAllowed(_ => true)` with `AllowCredentials()` echoes every origin and lets any site read authenticated responses. 2. A suffix check such as `origin.EndsWith("coffee.example")` also matches a host registered as `evilcoffee.example`. 3. A wildcard subdomain policy trusts takeover-prone subdomains. Keep the predicate an allow-list, log rejected origins at a level you actually collect, and keep public, non-credentialed endpoints on a separate policy so the credentialed one stays narrow. ## Testing the policy The predicate is ordinary code, so test it like code: - Unit-test the function behind `SetIsOriginAllowed` with the cases that matter: an active tenant, a suspended tenant, `http://` instead of `https://`, a look-alike host such as `north-shops.coffee.example`, a host with an extra suffix, and the literal `null` origin a sandboxed frame sends. - In an integration test with `WebApplicationFactory<Program>`, send a request with an `Origin` header and assert on `Access-Control-Allow-Origin`, `Access-Control-Allow-Credentials` and `Vary` in the response; send an `OPTIONS` request with `Access-Control-Request-Method` to check the preflight answer. - Re-run those tests whenever the tenant registry's refresh logic changes, since a stale cache shows up as a CORS error for a newly onboarded tenant rather than as an exception.

  • Why can't the ASP.NET Core SetIsOriginAllowed predicate query the tenant database directly?
    It is a synchronous `Func<string, bool>` called on every cross-origin request, so a database call would block a thread per request. Keep the allowed hosts in a singleton cache refreshed in the background, or implement `ICorsPolicyProvider`, whose `GetPolicyAsync` can await the lookup.
  • Does SetIsOriginAllowedToAllowWildcardSubdomains with https://*.shops.coffee.example also allow https://shops.coffee.example itself?
    No. The wildcard check requires the origin's host to end with `.shops.coffee.example` and to share the scheme and port; the bare domain has no leading label. List it as a separate `WithOrigins` entry if the apex storefront also calls the API.

  • SetIsOriginAllowed(_ => true) with AllowCredentials() is fine because the builder did not throw.
  • origin.EndsWith("coffee.example") is a safe tenant check.
  • SetIsOriginAllowedToAllowWildcardSubdomains matches subdomains even without a *. entry in WithOrigins.
  • Vary: Origin is unnecessary when each response echoes the caller's own origin.
  • The SetIsOriginAllowed predicate can await a database query per request.