Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Asp.Net Core

ASP.NET Core: Fix a CORS Policy That Throws at Startup Because AllowCredentials Was Combined With AllowAnyOrigin

- 22.10.26 - ErcanOPAK

⚙️ The CORS Policy That Was Never Actually Allowed to Exist

AllowAnyOrigin and AllowCredentials are individually reasonable CORS settings, but the CORS specification itself forbids combining them, because a server that both accepts cookies or auth headers and announces it will accept requests from literally any origin would hand any malicious site on the internet a working credentialed session – ASP.NET Core’s CORS middleware enforces that restriction not with a confusing runtime CORS failure in the browser, but with an immediate InvalidOperationException thrown the moment the app actually tries to apply a policy combining both, which usually means right at startup if the policy is exercised during the very first request.

🔎 The Problem

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.AllowAnyOrigin()      // accept requests from anywhere
              .AllowAnyHeader()
              .AllowCredentials();   // ...and also send credentials
    });
});

// System.InvalidOperationException:
// The CORS protocol does not allow specifying a wildcard origin
// (AllowAnyOrigin) and credentials at the same time. Configure the
// CORS policy by listing individual origins if credentials needs to
// be supported.
//
// This throws as soon as the policy is evaluated against an actual
// cross-origin request - often effectively "at startup" in dev,
// since the frontend's very first API call triggers it immediately.

✅ Fix: List Explicit Origins Whenever Credentials Are Needed

  • Replace AllowAnyOrigin() with WithOrigins(“https://app.example.com”, “https://staging.example.com”) listing every explicit origin that legitimately needs credentialed cross-origin access – this is the only configuration the CORS spec itself permits once AllowCredentials() is also in the policy, not an ASP.NET Core-specific limitation that can be worked around with a different method call.
  • If the set of allowed origins is genuinely dynamic (a multi-tenant app where each customer has their own subdomain), use SetIsOriginAllowed(origin => /* validate against a known list */) instead of a wildcard – this still lets AllowCredentials() coexist with it, because the decision resolves to one specific, validated origin per request rather than literally any origin.
  • If the API genuinely never needs to send cookies or use credentialed requests, dropping AllowCredentials() entirely and keeping AllowAnyOrigin() is a completely valid, simpler policy – the fix here isn’t inherently “always list explicit origins,” it’s making sure the credentials and wildcard-origin settings are never both true on the same policy.

🚨 Why This Is Dangerous

  • The exception happens at the exact moment a real cross-origin request needs the policy evaluated, which in development often means it looks like a transient, confusing crash tied to whichever endpoint happened to be called first, rather than an obviously misconfigured CORS policy sitting in Program.cs the whole time.
  • A policy copy-pasted from an older tutorial or a different project that genuinely needed just AllowAnyOrigin can pick up an added AllowCredentials() later – for a new feature needing cookie-based auth, say – without anyone registering that the two settings were never meant to be combined, since each one reads as reasonable in isolation.

AllowAnyOrigin and AllowCredentials each sound like a reasonable thing to want. Wanting both at once is the one combination CORS itself was specifically designed to refuse.

— Backend Architect

Related posts:

ASP.NET Core: Why a Custom Middleware Never Runs for Static File Requests

ASP.NET Core: Why a Custom Middleware Never Runs for Static File Requests

IHostedService vs BackgroundService

IHostedService vs BackgroundService

.NET Core: Use Options Pattern for Configuration

.NET Core: Use Options Pattern for Configuration

Views: 13

Post navigation

The AI Prompt That Turns a Phone Full of Kids’ Artwork and School Certificate Photos Into One Organized, Year-by-Year Memory Book
Visual Studio: Fix Go To Definition Jumping to Decompiled Metadata Instead of Your Own Source Because Source Link Was Never Enabled

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (607)
  • Average of all values in a column that are not zero in SQL (569)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com