ASP.NET Core:具有OPTIONS异常的Windows身份验证(CORS预检)

问题描述 投票:0回答:1

我正在处理单页Web应用程序。它具有ASP.NET Core 3后端和Angular 9前端。我在IIS Express的http://localhost:59280上的Visual Studio中运行后端。前端使用ng servehttp://localhost:4200的Visual Studio Code中运行。以前,我不需要在后端打开CORS,因为我只在Chrome中测试了该应用程序,并且添加--disable-web-security命令行参数足以关闭Same Origin Policy。在实时服务器上,不需要CORS,以上跨源情况仅发生在我的开发机上。

现在,我想在Firefox中调试前端,但是由于无法关闭Firefox的相同来源策略,因此我必须在后端打开CORS。不幸的是,它不起作用,因为我使用Windows身份验证,并且它会终止默认情况下未经身份验证的CORS preflight request。如果我可以让HTTP OPTIONS请求在没有Windows身份验证的情况下处理,则可以解决此问题。我认为可以通过在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,
    ...

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

是否有办法在ASP.NET Core 3应用程序中为HTTP OPTIONS请求分别关闭Windows身份验证?

angular asp.net-core cors same-origin-policy preflight
1个回答
0
投票

[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();
});

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

© www.soinside.com 2019 - 2024. All rights reserved.