nik*_*hta 5 http windows-authentication cors preflight angular
我在后端使用 Angular 4 和 ASP.NET Web api 2,并启用了 Windows 身份验证。我有一篇文章和一篇 get api。GET 工作正常。但对于 POST 我收到此错误
预检响应具有无效的 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;
});
Run Code Online (Sandbox Code Playgroud)
我已在 Web 配置中设置所有 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" />
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
我尝试删除
headers: new Headers({
'content-type': 'application/json'
})
Run Code Online (Sandbox Code Playgroud)
以下是我的 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
从我的角度代码,但它没有帮助。我还尝试将其替换为“text/html”,但这也不起作用。有人可以告诉我我做错了什么吗?我认为如果它适用于 GET,它应该可以正常工作。
我读过的所有主题都表明您不能完全禁用匿名身份验证,否则 OPTIONS 飞行前请求将不起作用。这是因为:
根据 W3C 规范,浏览器从 CORS 预检中排除用户凭据:
请参阅此主题,例如:带有 Windows 身份验证的 WebAPI CORS - 允许匿名选项请求
基本上,解决方案是允许 OPTIONS 调用无需身份验证即可通过。为此,需要启用匿名身份验证。
在这个问题中:401 response for CORS request in IIS with Windows Authenabled 答案建议使用以下 web.config
<system.web>
<authentication mode="Windows" />
<authorization>
<allow verbs="OPTIONS" users="*"/>
<deny users="?" />
</authorization>
</system.web>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6684 次 |
| 最近记录: |