How to enable Cors for every type of request in asp.net core 3.1?
I am following the MS Docs but they seem to not work.
Note: I am able to achieve cors for specific domains but not to every domain. For example the below configuration I have applied to my project:
In the ConfigureServices();
method I added:
services.AddCors();
In the Configure()
method I added:
app.UseCors(builder => { builder .WithOrigins() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); });
But when I try to access the API with jQuery from another url then I get:
Access to XMLHttpRequest at 'https://localhost:44314/Reservation' from origin 'https://localhost:44361' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now If i put the URL in the WithOrigins() method I am able to access the API:
app.UseCors(builder =>
{
builder
.WithOrigins("https://localhost:44361")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
My question is how to give access to the API to every URL(i.e domain, subdomain,etc) without restriction. Applying * does not work.
Please help.
you need to allow any origin which you do with the following:
builder.AllowAnyOrigin()
Any Origin with AllowCredentials
not allowing credentials to be sent from any origin is by design.
You can get around this by using the following
builder.SetIsOriginAllowed(_ => true)
I dont think it is a great solution because it removes the benefit of useCredentials().
Note
useCredentials
is not required for sending a JWT in the header. It is for if you need to send cookies in the request. Allowing any origin and enabling useCredentials
can lead to security vunerabilities which is why it is not allowed by default.
For more information you should read
What exactly does the Access-Control-Allow-Credentials header do?
and
CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true