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

蓝咒 提交于 2021-01-29 19:35:55

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/60036979/net-core-allowing-sending-back-error-401-when-using-cors-instead-of-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!