Nimish David Mathew
Nimish David Mathew

Reputation: 3168

No 'Access-Control-Allow-Origin' header is present on the requested resource when 401 response is returned from the server

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".

Upvotes: 9

Views: 2537

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93083

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.

Upvotes: 20

Related Questions