I have a .NET Core 3.0 and Angular 8 web application. I have enabled CORS in Startup.cs and it works fine. I am using JWT authentication along with an interceptor on the angular side to append JWT token to each request. The call to a route with [Authorize] attribute is successful when the token is valid. When the token is expired/invalid, the server returns 401 as expected. But, the angular interceptor is not able to recognize the 401 error since there is a CORS issue as seen in the console error:
Access to XMLHttpRequest at 'https://localhost:5001/api/Users/test' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
On inspecting the response I could see that there were no Access-Control-Allow-Origin headers present in the response. Why does that happen? Please note that this does not happen if the token is valid.
Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Angular recieves the error status as status: 0, statusText: "Unknown Error".
To avoid the error "No 'Access-Control-Allow-Origin' header is present on the requested resource," verify the following: The origin's cross-origin resource sharing (CORS) policy allows the origin to return the "Access-Control-Allow-Origin" header.
"No 'access-control-allow-origin' header present" is up there as one of the least helpful error messages. Searching for it on the internet is likely to bring up a Stack-Overflow answer that is worse than wrong – it's dangerous.
Check if the origin returns the "Access-Control-Allow-Origin" header by running a curl command similar to the following: If the CORS policy allows the origin to return the header, the command returns a message similar to the following:
The browser will not allow you to get the sensitive data from other domain, for the security purpose your browser will return you “No ‘Access-Control-Allow-Origin'”. To overcome this, we have something called Cross Origin Resource Sharing (CORS).
UseCors should be placed above UseAuthentication and UseAuthorization:
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
Otherwise, the CORS middleware will not run when the authorization middleware short-circuits the pipeline and so will not add the CORS headers. This is something that's a little different in ASP.NET Core 3.0 with the introduction of UseAuthorization, but the middleware ordering has always been important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With