【问题标题】:could not post to asp.net core web api using windows authentication无法使用 Windows 身份验证发布到 asp.net core web api
【发布时间】:2019-08-11 08:01:21
【问题描述】:

API 是 AspNetCore WebApi,默认配置为 Windows 身份验证并启用了 CORS。客户端是带有 GET 和 POST 方法的 Angular。

GET调用成功:

this.http.get("https://localhost:44358/api/values", {withCredentials:true})
  .subscribe(a=> {
    console.log(a);
    this.list=a;        
  });

POST 失败:

this.http.post("https://localhost:44358/api/values", {value:"aaa"}, {withCredentials:true})
  .subscribe(a=> {
    console.log(a);
    this.list=a;        
  });

02个例外是

OPTIONS https://localhost:44358/api/values 401 (Unauthorized)

Access to XMLHttpRequest at 'https://localhost:44358/api/values' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

有什么想法吗?

【问题讨论】:

  • 这是 CORS 的问题,而不是 Angular 的问题。错误很明显,您需要在后端实现“Access-Control-Allow-Origin”标头。在您的情况下,CORS 的原因是应用程序的不同端口(客户端和服务器)。 PS。确保您允许 OPTIONS 请求,这是使 CORS 工作所必需的。

标签: angular cors asp.net-core-webapi windows-authentication


【解决方案1】:

POST 导致浏览器在真正的 POST 之前将 OPTIONS 发送到 web api。然而,webapi 拒绝了这个调用,因为配置仅基于 Windows 身份验证。解决方案是为控制器启用 Windows 身份验证以及launchSetting.json 中的 OPTIONS 匿名身份验证。

"iisSettings": {
"windowsAuthentication": true, 
"anonymousAuthentication": true, 

并在Startup.cs中的AddMvc之前添加1行

services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

【讨论】:

  • 如果我不想启用anonymousAuthentication怎么办?没有别的办法吗?
猜你喜欢
  • 2016-12-22
  • 2017-06-28
  • 2017-10-22
  • 1970-01-01
  • 2022-01-27
  • 2018-01-28
  • 2017-11-24
  • 2019-09-03
  • 1970-01-01
相关资源
最近更新 更多