Angular 4 HTTP POST与Windows身份验证预检问题



我在启用了Windows身份验证的后端使用带有 ASP.NET Web API 2的角度4。我有一个帖子和一个获取 api。GET工作正常。但是对于开机自检,我收到此错误

预检响应具有无效的 HTTP 状态代码 401

这意味着我收到未经授权的 OPTIONS 方法错误,我知道不应该是这种情况,因为 OPTIONS 方法永远不会使用用户凭据调用。

在角度中,我调用 api 如下

let requestOptions = new RequestOptions({
withCredentials: true,
headers: new Headers({
'content-type': 'application/json'
})
})
this.http.post("someapiendpoint", JSON.stringify(data), requestOptions).subscribe(data => {
debugger;
});

我已经在我的网络配置中设置了所有 CORS 标头,如下所示

<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />

我在web.config的身份验证块中也有以下内容

<authentication>
<anonymousAuthentication enabled="false" userName="" />
<basicAuthentication enabled="false" />
<clientCertificateMappingAuthentication enabled="false" />
<digestAuthentication enabled="false" />
<iisClientCertificateMappingAuthentication enabled="false">
</iisClientCertificateMappingAuthentication>
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>

我尝试删除

headers: new Headers({
'content-type': 'application/json'
})

以下是我的 Web API 控制器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace Backend.Controllers
{
public class DemoController : ApiController
{
Entities db = new Entities();
public DemoController ()
{
}
[HttpPost]
[ActionName("postevent")]
public IHttpActionResult PostEvent(Demo data)
{
db.Demos.Add(data);
db.SaveChanges();
return Ok();
}
}
}

从我的角度代码,但它没有帮助。我也试图用"text/html"替换它,但这也没有用。有人能告诉我我做错了什么吗?正如我认为如果它适用于 GET 应该可以正常工作。

我读过的所有主题都指出,您不能完全禁用匿名身份验证,否则 OPTIONS 预检请求将不起作用。这是因为:

根据 W3C 规范,浏览器将用户凭据排除在 CORS印前检查:

请参阅本主题,例如:具有 Windows 身份验证的 WebAPI CORS - 允许匿名选项请求

基本上,解决方案是允许 OPTIONS 调用在没有身份验证的情况下通过。为此,需要启用匿名身份验证。

在此问题中:启用了 Windows 身份验证的 IIS 中 CORS 请求的 401 响应 答案建议以下web.config

<system.web>
<authentication mode="Windows" />
<authorization>
<allow verbs="OPTIONS" users="*"/>
<deny users="?" />
</authorization>
</system.web>

保罗的回答是正确的。我有完全相同的设置,它工作正常。

您需要确保同时启用匿名和 Windows 身份验证,将 Paul 的答案中的代码段添加到 web.config 以允许未经身份验证的选项请求,并在控制器上添加 [Authorize] 属性。

最新更新