Search code examples
apiasp.net-corecorshttp-status-codes

.net core allowing sending back error 401 when using CORS (instead of zero)


My client JS app is receiving status code 0 when it is actually 401.
When I use postman for running the same request i am getting 401 as expected.

I have enabled cors as the following:

services.AddCors(o => o.AddPolicy("cors", builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .AllowCredentials();
            }));

....
app.UseCors("cors");

The cors is working when there is no authentication problem (401).

I am getting error code 0 in the client-side when it is supposed to be 401.

enter image description here


Solution

  • The cause of this error is a most likely a combination of CORS on your server and the web browser.

    Cause: My guess is, some of the required CORS headers are missing from your server response. Browsers return a status of 0 when incorrect Cors headers are used.

    Solution: Again I will guess the order you are registering your middleware is incorrect. As per the docs:

    With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints. Incorrect configuration will cause the middleware to stop functioning correctly.

    I would register you middleware in an order like so (depending on what middlewares you're using):

    app.UseRouting();
    app.UseCors("cors");
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    ...
    //register app.UseMvc(); last