从服务器返回 401 响应时,请求的资源上不存在“Access-Control-Allow-Origin”标头

Nim*_*hew 4 c# cors asp.net-core angular

我有一个 .NET Core 3.0 和 Angular 8 Web 应用程序。我在 Startup.cs 中启用了 CORS,它工作正常。我在角度端使用 JWT 身份验证和拦截器将 JWT 令牌附加到每个请求。[Authorize]当令牌有效时,调用具有属性的路由成功。当令牌过期/无效时,服务器按预期返回 401。但是,角度拦截器无法识别 401 错误,因为控制台错误中存在 CORS 问题:

从源“ http://localhost:4200 ”访问“ https://localhost:5001/api/Users/test ”的XMLHttpRequest已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头在请求的资源上。

在检查响应时,我可以看到响应中没有Access-Control-Allow-Origin标头。为什么会这样?请注意,如果令牌有效,则不会发生这种情况。

启动.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();
    });
}
Run Code Online (Sandbox Code Playgroud)

Angular 将错误状态接收为status: 0, statusText: "Unknown Error".

Kir*_*kin 11

UseCors应该放在上面UseAuthenticationUseAuthorization

app.UseCors(builder => builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader());

app.UseAuthentication();
app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)

否则,当授权中间件使管道短路时,CORS 中间件将不会运行,因此不会添加 CORS 标头。这与 ASP.NET Core 3.0 中的 引入有点不同UseAuthorization,但中间件排序一直很重要。