【问题标题】:Web API + CORS + Basic NTLM: 401 with Firefox + ChromeWeb API + CORS + 基本 NTLM:401 与 Firefox + Chrome
【发布时间】:2014-12-24 15:29:31
【问题描述】:

所以我一直在寻找我能找到的关于这个主题的所有帖子,但仍然没有弄清楚。希望你能帮忙:

启用 CORS 的 Web API 2:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

web.config:

<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows" /> 
</system.web>

jQuery

<script>
$(document).ready(function()
{
    $("button").click(function()
    {
        var endpoint = "http://localhost:82/api/test";
        var base64Credentials = window.btoa("domain\credentials:password");

        $.ajax({
            url: endpoint,
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
                xhr.setRequestHeader("Authorization", "Basic " + base64Credentials);
            },
            success: function(result) {
                alert(result);
            }
        }); 
    });
});
</script>

IIS 已启用基本身份验证。

基本身份验证适用于 IE。 Firefox 和 Chrome 受预检 OPTIONS 调用的约束。

使用 Fiddler,我可以看到,如果我将 IIS 设置为同时允许匿名身份验证和基本身份验证,那么 OPTIONS 调用将导致 200,然后使用基本身份验证的后续 GET 启动,一切正常。如果我关闭匿名,那么我会在 OPTIONS 调用中收到 401。

问题:

是否需要同时允许匿名和基本身份验证才能支持此用例?

【问题讨论】:

    标签: asp.net authentication asp.net-web-api cross-domain


    【解决方案1】:

    我在我的一个项目中部分解决了这个问题。 它在 IE 中始终有效,但在 Chrome 中,我仍然会收到对请求的随机 401 回复,但是当我检查响应时,Web api 正在将 JSON 数据发回,因此它通过了 OPTIONS。

    Web API 的 IIS 站点配置为:

    • Windows 身份验证,匿名禁用;
    • 在 Windows 身份验证提供程序(右侧选项)下,将 NTLM 移到顶部

    在您的 web.config 中:

    <httpProtocol>
      <customHeaders>
        <!-- Allows auth in CORS AJAX requests -->
        <add name="Access-Control-Allow-Credentials" value="true" />
        <!-- May only ever be one value - a domain or "*".  "*" is disallowed when Access-Control-Allow-Credentials is true -->
        <add name="Access-Control-Allow-Origin" value="http://localhost:63415" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Headers, Access-Control-Request-Method" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, HEAD, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    

    在 Global.asax.cs 中

        protected void Application_BeginRequest()
        {
            // When Chrome sends the OPTIONS it breaks on windows auth, so this fixes it.
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.StatusCode = (int)HttpStatusCode.OK;
                Response.Flush();
            }
        }
    

    所有这些都没有使用 CORS NuGet 包。我试过了,但我仍然遇到 OPTIONS 问题。

    编辑:对此进行更新,现在 Chrome 对我来说似乎一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-11
      • 2019-10-17
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多