kol*_*kol 2 same-origin-policy cors preflight asp.net-core angular
我正在开发一个单页网络应用程序。它具有ASP.NET Core 3后端和Angular 9前端。我在 Visual Studio 中的 IIS Express 上运行后端,网址为http://localhost:59280。前端在 Visual Studio Code 中运行,使用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>
Run Code Online (Sandbox Code Playgroud)
...但我收到一条错误消息:“此配置节不能在此路径上使用。当该节被锁定在父级别时,就会发生这种情况。” 显然 web.config 与launchSettings.json冲突,后者似乎在 Visual Studio 中的 IIS Express 上运行后端时控制身份验证,使用以下两行:
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
...
Run Code Online (Sandbox Code Playgroud)
我不知道如何仅使用 launchSettings.json 单独关闭 HTTP OPTIONS 请求的 Windows 身份验证。
有没有办法在 ASP.NET Core 3 应用程序中单独关闭 HTTP OPTIONS 请求的 Windows 身份验证?
1)上述 web.config 设置有效,我只需解锁 .vs 目录中 applicationhost.config 中的“anonymousAuthentication”部分:<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();
});
Run Code Online (Sandbox Code Playgroud)
3)我还必须{ withCredentials: true }
在 Angular 9 前端添加 HttpClient.post() 的参数。如果没有这个,OPTIONS 请求会得到 204,但后续的 POST 会得到 401。