我已经建立了一个SPA网站,其前端为Angular,服务器端为asp.net Core Web Api 3.0。
由于到目前为止this article到目前为止一切顺利,我正在尝试配置Windows身份验证!但是...当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标头时,angular内的状态代码为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标头由授权中间件保留吗?
结果证明所有配置都正确,差不多!
问题仅是在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(); });