ASP.NET核心:OPTIONS异常的Windows身份验证(CORS预飞行)



我正在开发一个单页web应用程序。它有ASP.NET Core 3后端和Angular 9前端。我在IIS学习版的Visual Studio中运行后端,位于http://localhost:59280.前端在Visual Studio代码中运行,使用ng serve,位于http://localhost:4200.以前我不需要在后端打开CORS,因为我只在Chrome中测试了该应用程序,添加--disable-web-security命令行参数就足以关闭同源策略。在实时服务器上不需要CORS,上面的跨源情况只发生在我的开发机器上。

现在我想在Firefox中调试前端,但由于无法关闭Firefox的同源策略,我必须在后端打开CORS。不幸的是,它不起作用,因为我使用Windows身份验证,并且默认情况下它会停止未经身份验证的CORS预飞行请求。如果我可以在不使用Windows身份验证的情况下处理HTTP OPTIONS请求,则可以解决此问题。我想这可以通过在web.config:中添加这样的东西来完成

<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" />
</authentication>
<authorization>
<add accessType="Allow" verbs="OPTIONS" users="*" />
</authorization>
</security>
</system.webServer>

但我收到了一条错误消息:"此配置节不能在此路径上使用。当该节在父级锁定时会发生这种情况。"显然,web.config与launchSettings.json冲突,后者似乎在Visual Studio中的IIS Express上运行后端时使用以下两行控制身份验证:

{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
...

我不知道如何单独关闭HTTP OPTIONS请求的Windows身份验证,只使用launchSettings.json.

在ASP.NET Core 3应用程序中,是否有方法为HTTP OPTIONS请求单独关闭Windows身份验证

1(上述web.config设置有效,我只需要解锁.vs目录中applicationhost.config中的"匿名身份验证"部分:<section name="anonymousAuthentication" overrideModeDefault="Allow" />。launchSettings.json中"anonymousAuthentication"参数的值无关紧要。

2(根据@MartinStaufcik的建议,我在StartUp.Configure((的开头添加了一个中间件,它响应飞行前请求(MDN(:

app.Use(async (context, next) => {
if (context.Request.Method == "OPTIONS") {
context.Response.StatusCode = 204;
context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
context.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
return;
}
await next();
});

3(我还必须将{ withCredentials: true }添加到Angular 9前端的HttpClient.post((的参数中。如果没有这一点,OPTIONS请求得到204,但随后的POST得到401。

最新更新