I set CORS in my .net core application like this:
app.UseCors(builder => builder
.WithOrigins("https://*.example.com")
.SetIsOriginAllowedToAllowWildcardSubdomains()
.SetIsOriginAllowed(origin => _configuration.GetSection("Cors:AllowedOrigins").Get<IList<string>>().Contains(origin))
.AllowAnyHeader()
.AllowAnyMethod());
The server response header is:
access-control-allow-origin: https://*.example.com
So I don't understand why I get this error because it looks like it has support for any sub-domain.
This is the full error:
login:1 Access to fetch at 'https://staging.example.com/' from origin 'https://app.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://*.example.com' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Any idea why I get this error even though I try to access from a sub-domain of example.com
?
CodePudding user response:
I solved this by changing the middleware order like is suggested in the official Microsoft docs.
Even though in Microsoft docs they mention the option to allow sub-domains it didn't work for me and I had to add them explicitly.
This is the order of my middleware in startup.cs:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(builder => builder
.WithOrigins(_configuration.GetSection("Cors:AllowedOrigins").Get<string[]>())
.AllowAnyHeader()
.AllowAnyMethod());
app.UseAuthentication();
app.UseAuthorization();
// custom middlewares
app.UseRequestResponseLogging();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
});
appsettings:
"Cors": {
"AllowedOrigins": [
"https://example.com",
"https://sub.example.com",
"https://tests.example.com",
"https://staging.example.com"
]
}
CodePudding user response:
you did not say the .NET core version, Anyway in your Startup.cs define policy like:
services.AddCors(opt =>
{
opt.AddPolicy("examplePolicy", builder =>
{
builder.AllowAnyOrigin("https://*.example.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
then
app.UseCors("examplePolicy");
Finally, the API:
[EnableCors("examplePolicy")]
[HttpGet("...")]
public void yourAPI()
{
}