【发布时间】: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