skip to content

Why does an ASP.NET Core CORS policy combining AllowAnyOrigin with AllowCredentials throw, and how do you let the storefront send cookies instead?

level: middleimportance: must knowfreq 64%

answer

  1. the wildcard plus credentials
  2. CorsPolicyBuilder.Build() guard
  3. InvalidOperationException at startup
  4. WithOrigins(...).AllowCredentials() echoes Origin
  5. Vary: Origin when the answer varies

basics

~10 s

AllowAnyOrigin makes the policy answer Access-Control-Allow-Origin: *, which browsers never accept on a credentialed request, so CorsPolicyBuilder.Build() throws InvalidOperationException. List the storefront with WithOrigins and add AllowCredentials.

solid answer

~40 s

`CorsPolicyBuilder.Build()` checks for `AllowAnyOrigin` together with `SupportsCredentials` and throws `InvalidOperationException` ("The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time"). It fails fast because `AllowAnyOrigin` writes the literal `*` into `Access-Control-Allow-Origin`, and a browser rejects `*` on a request that carries cookies. With `UseCors` in the pipeline the policy is built while the app starts, so the app fails at startup. The fix is `WithOrigins("https://shop.coffee.example").AllowCredentials()`: the middleware then echoes the request's own `Origin`, adds `Access-Control-Allow-Credentials: true`, and adds `Vary: Origin` when more than one origin or a custom predicate is configured. `SetIsOriginAllowed(_ => true)` with `AllowCredentials()` gets past the check but rebuilds the same hole.

code

csharp · 11 lines
csharp
builder.Services.AddCors(options =>
{
    // Throws InvalidOperationException when the policy is built:
    // options.AddPolicy("Storefront", p => p.AllowAnyOrigin().AllowCredentials());

    options.AddPolicy("Storefront", policy => policy
        .WithOrigins("https://shop.coffee.example", "https://www.coffee.example")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials());
});

go deeper

for a junior

Remember the rule: no AllowAnyOrigin with AllowCredentials. List the storefront's origin explicitly instead.

for a middle

Explain where the InvalidOperationException comes from, when it fires, and which headers WithOrigins plus AllowCredentials produce, including Vary: Origin.

for a senior

Spot SetIsOriginAllowed(_ => true) with credentials in review and explain why it reopens the hole the guard closes; keep credentialed and public policies separate.

for a principal

Weigh cookie-based sessions across origins against token-based calls or a same-origin proxy, considering CSRF exposure and how many origins must be governed.

## The guard in `CorsPolicyBuilder` A **credentialed** cross-origin request is one where the browser attaches cookies or other credentials, for example `fetch(url, { credentials: "include" })` from the storefront. The CORS rules forbid answering such a request with the wildcard `Access-Control-Allow-Origin: *`; the server must name the origin. ASP.NET Core encodes that rule in two places: - **`CorsPolicyBuilder.Build()`** throws **`InvalidOperationException`** when the policy has `AllowAnyOrigin` and `SupportsCredentials` both set. The message reads: "The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported." - **`CorsService.EvaluatePolicy`** repeats the check per request and throws **`ArgumentException`**, which catches a `CorsPolicy` object assembled by hand and passed to `AddPolicy(name, CorsPolicy)` without going through the builder. `WithOrigins("*")` trips the same guard: a policy whose origin list is exactly `*` reports `AllowAnyOrigin == true`. ## When the exception appears `AddCors(options => options.AddPolicy(...))` only queues a configure delegate. The delegate runs, and `Build()` with it, the first time `IOptions<CorsOptions>` is read. `CorsMiddleware` takes an `ICorsService` in its constructor, `CorsService` reads the options in its constructor, and conventional middleware is constructed while the request pipeline is built. So with `app.UseCors(...)` in `Program.cs`, the bad policy stops the app **at startup** rather than serving an insecure header. A policy passed to `RequireCors(p => ...)` or `UseCors(p => ...)` is built right at that call. ## The working configuration ```csharp options.AddPolicy("Storefront", policy => policy .WithOrigins("https://shop.coffee.example", "https://www.coffee.example") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials()); ``` For a request from an allowed origin the middleware writes: | Header | Value | Why | |---|---|---| | `Access-Control-Allow-Origin` | the request's own `Origin` | an explicit origin is legal with credentials | | `Access-Control-Allow-Credentials` | `true` | written because `SupportsCredentials` is set | | `Vary` | `Origin` | added because the policy lists more than one origin, so the answer depends on the request | `Vary: Origin` matters to any cache in between: without it a cached response for one origin could be replayed to another. ASP.NET Core adds it when the origin list has more than one entry or when a custom origin predicate is set; a single listed origin and the default predicate add none. ## Why `AllowAnyHeader` and `AllowAnyMethod` are not refused Only the origin is guarded. ASP.NET Core's `AllowAnyHeader` and `AllowAnyMethod` do **not** emit `*`: on a preflight they **echo** the values from `Access-Control-Request-Headers` and `Access-Control-Request-Method`. An echoed list is valid with credentials, so the builder allows the combination. ## The bypass that looks like a fix - `SetIsOriginAllowed(_ => true)` combined with `AllowCredentials()` builds without error, because the guard checks `AllowAnyOrigin`, not the predicate. - The middleware then echoes **any** origin and adds `Access-Control-Allow-Credentials: true`, which lets every site read the user's authenticated responses. - The ASP.NET Core docs name this as an insecure configuration. Use a predicate only when it checks the origin against a real allow-list. ## Checklist for a cookie-authenticated SPA 1. List the storefront origins explicitly with `WithOrigins`, from configuration. 2. Add `AllowCredentials()` to that policy only, not to a public read policy. 3. Make sure the client opts in (`credentials: "include"` in `fetch`); the server header alone sends no cookie. 4. Keep CSRF protection on state-changing endpoints: a cookie the browser attaches cross-origin is exactly what a forged request relies on. 5. Watch the logs at startup: an `InvalidOperationException` from `CorsPolicyBuilder.Build` names this exact rule. ## How the pieces line up end to end For the storefront's "pause my subscription" button to work with a session cookie, three independent things must agree: - **The browser request opts in.** `fetch` sends cookies cross-origin only with `credentials: "include"` (or `withCredentials` on `XMLHttpRequest`). - **The preflight answer grants it.** For a non-simple call, the `204` preflight response must carry the echoed origin and `Access-Control-Allow-Credentials: true`; a policy without `AllowCredentials()` fails here even though the origin matched. - **The actual response grants it again.** The same two headers must appear on the real response, which `CorsMiddleware` adds through its response-starting callback. If any one of them is missing, the storefront's script sees a CORS error and the user's cookie-backed session appears not to work, even though the API may have processed the request. Interviewers like this question precisely because the fix is one builder call, while the reason runs through the browser, the middleware and the policy object.

  • Can you get round the ASP.NET Core guard by building a CorsPolicy object by hand and passing it to AddPolicy?
    It skips `CorsPolicyBuilder.Build()`, but `CorsService.EvaluatePolicy` repeats the check on every request and throws `ArgumentException` with the same message. The rule is enforced both when the policy is built and when it is applied, so the only legal credentialed configuration names its origins.
  • Why does a policy with a single WithOrigins entry send no Vary: Origin header?
    `CorsService` sets `VaryByOrigin` only when the policy lists more than one origin or uses a custom `IsOriginAllowed` predicate. With one fixed origin the allowed response is the same for every request that gets the header, so ASP.NET Core leaves `Vary` alone; requests from other origins simply receive no CORS headers.

  • SetIsOriginAllowed(_ => true) with AllowCredentials() is a safe fix for the exception.
  • AllowAnyHeader() is also rejected with AllowCredentials() because it sends a wildcard.
  • The exception only appears on the first cross-origin request, so startup cannot catch it.
  • AllowCredentials() makes the browser attach cookies without any client-side opt-in.
  • DisallowCredentials() is needed to fix the exception while keeping cookies working.