【问题标题】:How to add CORS headers to 401/403 responses?如何将 CORS 标头添加到 401/403 响应?
【发布时间】:2020-03-16 11:17:25
【问题描述】:

我已经在前端使用 Angular 并在服务器端使用 asp.net Core Web Api 3.0 构建了一个 spa 网站。

我正在尝试配置 Windows 身份验证,感谢 this article 到目前为止一切顺利!但是......当 Api 正确返回 401/403 时,CORS 标头存在问题,cors 标头丢失。这是一个例子:

General:
Status Code: 403 Forbidden
Remote Address: [::1]:44389
Referrer Policy: no-referrer-when-downgrade
Response-Headers:
Date: Wed, 20 Nov 2019 16:33:57 GMT
Persistent-Auth: true
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
X-Powered-By: ASP.NET

这是我使用[Authorise] 属性时生成的。我遇到的问题是,当 CORS 标头丢失时,角度内的状态码为 0,因此我的 http 拦截器不知道未经授权,无法正确处理重定向。

我尝试使用StartUp 中的中间件手动添加标头:

app.Use(async (context, next) =>
{
    context.Response.OnStarting(() =>
    {
        context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");

        return Task.FromResult(0);
    });

    await next();
});

但这不起作用,中间件仍然删除标题。

有趣的是,如果我删除授权属性并在控制器方法中返回 401/403:

[HttpGet]
public IActionResult Get()
    => Unauthorized();

CORS 标头是这样返回的:

Response-Headers:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200  

这是不可行的!

有人知道如何确保授权中间件保留 CORS 标头吗?

【问题讨论】:

  • 您的 Web 服务器和 API 服务器是否不同或运行在不同的端口上?
  • 是的,它们在不同的端口上运行

标签: angular cors authorization asp.net-core-webapi


【解决方案1】:

事实证明一切都配置正确,差不多!

问题只是在StartUp 类中配置中间件的顺序。我不知道中间件的配置顺序对执行有影响。这是我的原始代码:

app.UseRouting();

app.UseAuthentication()
   .UseAuthorization();

app.UseCors(builder => builder.WithOrigins("http://localhost:4200")
                                      .AllowCredentials()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader());

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

配置 Cors BEFORE 身份验证修复了问题,现在中间件处理的未经授权的请求仍然包含 cors 标头。

app.UseRouting();

app.UseCors(builder => builder.WithOrigins("http://localhost:4200")
                                      .AllowCredentials()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader());
app.UseAuthentication()
   .UseAuthorization();

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

【讨论】:

    【解决方案2】:

    您能否发布完整的 startup.cs 文件的副本?我有同样的问题,并按照您的更改,但仍然收到 401。我试图访问 IIS 10 上设置为 Windows 身份验证的站点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-15
      • 2019-09-05
      • 2019-05-05
      • 2018-11-15
      • 2013-04-04
      • 2021-02-17
      • 2017-04-16
      • 2016-04-13
      相关资源
      最近更新 更多