I've configured the cors middleware according to https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#cors-with-named-policy-and-middleware-1
services.AddCors(options =>
{
options.AddPolicy(name: CorsPolicies.PortfolioPolicy,
builder =>
{
builder.WithOrigins("http://localhost:44376")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
Add after the UseRouting() middleware in Configure(...)
app.UseCors(CorsPolicies.PortfolioPolicy);
And on my controller
[ApiController]
[EnableCors(CorsPolicies.PortfolioPolicy)]
[Route("api/portfolio")]
public class PortfolioController : ControllerBase
{
....
}
However, it seems that my browser does not allow this request to go through.
On my client app (react app) this is how the call is made.
fetch(`${process.env.REACT_APP_API_URL}/api/portfolio`)
.then(response => {
return response.json();
})
.then((data) => {
return setAPIData(data.data);
})
This results in the following
Access to fetch at 'http://localhost:32360/api/portfolio' from origin 'http://localhost:44376' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
What I don't understand is why does it work in in asp.net core 2.1, I have another project which uses the same configuration pattern, and everything seems to be working as expected in that one. Also, it works if I AllowAnyOrigin().
CodePudding user response:
You are setting AllowCredentials()
and not sending any credentials it seems. If you don't have any credentials remove that.
Read more about that here: Docs
CodePudding user response:
I was having same issue with .Net5.0. You need to change your client fetch request with below example, it is mentioned into same MS docs which you are referring
fetch('https://www.example.com/api/test', {
credentials: 'include'
});
From MS Docs on Allowcredentials
The HTTP response includes an Access-Control-Allow-Credentials header, which tells the browser that the server allows credentials for a cross-origin request.
If the browser sends credentials but the response doesn't include a valid Access-Control-Allow-Credentials header, the browser doesn't expose the response to the app, and the cross-origin request fails.
Allowing cross-origin credentials is a security risk. A website at another domain can send a signed-in user's credentials to the app on the user's behalf without the user's knowledge. The CORS specification also states that setting origins to "*" (all origins) is invalid if the Access-Control-Allow-Credentials header is present.