gpt4 book ai didi

angularjs - 带有 Windows 身份验证的 WebAPI CORS - 允许匿名 OPTIONS 请求

转载 作者:行者123 更新时间:2023-12-03 14:40:44 26 4
gpt4 key购买 nike

我有一个使用 Windows 身份验证运行的 WebAPI 2 REST 服务。它与网站分开托管,因此我使用 ASP.NET CORS NuGet 包启用了 CORS。我的客户网站正在使用 AngularJS。

到目前为止,这是我所经历的:

  • 我没有设置 withCredentials,因此 CORS 请求返回 401。通过将 withCredentials 添加到我的 $httpProvider 配置中解决。
  • 接下来,我使用通配符来源设置了我的 EnableCorsAttribute,这在使用凭据时是不允许的。通过设置明确的来源列表来解决。
  • 这使我的 GET 请求成功,但我的 POST 发出了预检请求,并且我没有创建任何 Controller 操作来支持 OPTIONS 动词。为了解决这个问题,我将 MessageHandler 实现为全局 OPTIONS 处理程序。它只是为任何 OPTIONS 请求返回 200。我知道这并不完美,但目前在 Fiddler 中有效。

  • 我被困在哪里 - 我的 Angular 预检调用不包括凭据。根据 this answer ,这是设计使然,因为 OPTIONS 请求被设计为匿名的。但是,Windows 身份验证使用 401 停止请求。

    我尝试将 [AllowAnonymous] 属性放在我的 MessageHandler 上。在我的开发计算机上,它可以工作 - OPTIONS 动词不需要身份验证,但其他动词需要。但是,当我构建并部署到测试服务器时,我的 OPTIONS 请求继续收到 401。

    使用 Windows 身份验证时,是否可以在我的 MessageHandler 上应用 [AllowAnonymous]?如果是这样,有关如何执行此操作的任何指导?或者这是错误的兔子洞,我应该寻找不同的方法?

    更新:
    我能够通过在 IIS 中的站点上设置 Windows 身份验证和匿名身份验证来使其工作。这导致一切都允许匿名,所以我添加了一个全局过滤器 Authorize,同时在我的 MessageHandler 上保留 AllowAnonymous。

    但是,这感觉像是一种 hack……我一直都明白,应该只使用一种身份验证方法(不能混合使用)。如果有人有更好的方法,我会很高兴听到它。

    最佳答案

    我一直在努力使 CORS 请求在以下限制内工作(与 OP 的非常相似):

  • 所有用户的 Windows 身份验证
  • 不允许匿名身份验证
  • 适用于 IE11,in some cases ,不发送 CORS 预检请求(或至少不作为 OPTIONS 请求到达 global.asax BeginRequest)

  • 我的最终配置如下:

    web.config - 允许未经身份验证(匿名)的预检请求(选项)
    <system.web>
    <authentication mode="Windows" />
    <authorization>
    <allow verbs="OPTIONS" users="*"/>
    <deny users="?" />
    </authorization>
    </system.web>

    global.asax.cs - 正确回复允许来自另一个域的调用者接收数据的标题
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
    if (Context.Request.HttpMethod == "OPTIONS")
    {
    if (Context.Request.Headers["Origin"] != null)
    Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);

    Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, MaxDataServiceVersion");
    Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");

    Response.End();
    }
    }

    CORS 启用
    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    // all requests are enabled in this example. SupportsCredentials must be here to allow authenticated requests
    var corsAttr = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
    config.EnableCors(corsAttr);
    }
    }

    protected void Application_Start()
    {
    GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    关于angularjs - 带有 Windows 身份验证的 WebAPI CORS - 允许匿名 OPTIONS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27414487/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com