繁体   English   中英

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

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

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

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在请求的资源上。

在检查响应时,我可以看到响应中没有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();
    });
}

Angular 收到错误状态为status: 0, statusText: "Unknown Error"

UseCors应该放在UseAuthenticationUseAuthorization

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

app.UseAuthentication();
app.UseAuthorization();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM