.NET Core how to add any origin to CORS and allow credentials
When I was migrating from .NET Core 2.2 to 3.0 I faced with the following error:
System.InvalidOperationException: 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.
Issue
The core issue was in the code:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
Since SignalR
actually requires AllowCredentials
I tried to not specify exact origin for development.
Solution
Here is a workaround to use both wildcard for any origin and allowing credentials:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.SetIsOriginAllowed(_ => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
Just be careful to not use that kind of code in production - you probably don't want allowing any origin to make a handshake with SignalR
And here we go with these settings we won't get browserCross-Origin Request Blocked
and SignalR will make a handshake as usual.