【问题标题】:Unauthorized 401 on Post request Windows Authentication + Core 2.2 WebAPI发布请求时出现未经授权的 401 Windows 身份验证 + 核心 2.2 WebAPI
【发布时间】:2020-01-13 07:35:04
【问题描述】:

我正在使用带有 WebAPI 的 .CORE 2.2。 该解决方案托管在 IIS10 Windows Server 2016 上,Windows 身份验证应该是我的服务的唯一身份验证方法。 在 Angular 7 中,当我使用 withCredentials 设置为 true 的选项发出 GET 请求时。一切都按预期工作。这个 Post 请求无论如何都不起作用,并且响应是 Unauthorized 401。 仅供参考,API 和服务器 API 位于不同的服务器上。

post<T>(path, body = {}): Observable<T> {
   let requestheaders = new HttpHeaders({
      'Content-Type': 'application/json',
   });
   return this.http.post(this.getUrl(path), '{}', 
   { headers: requestheaders, withCredentials: true }) as Observable<T>;
}

这不是 Cors 政策,因为 Cors 配置正确

services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
      builder.WithOrigins("http://localhost:4200", 
            "https://localhost:4200")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
}));

app.UseCors("CorsPolicy");

关于如何处理这个问题的任何线索?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:
    • 在您的后端,将 AllowCredentialsSupportsCredentials 属性设置为 true
    • 在您的后端,不要将通配符 (*) 放入允许来源。专门添加您的前端网址

    像这样的

    .NET 核心

    services.AddCors(c =>
    {
       c.AddPolicy("AllowOrigin",
           options => options
                  .WithOrigins("http://localhost:4200") //Important
                  .AllowAnyMethod()
                  .AllowAnyHeader()
                  .AllowCredentials() //Important
        );
    });
    

     services.AddCors();
    
         var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();
    
         policy.Headers.Add("*");    
         policy.Methods.Add("*");          
         policy.Origins.Add("*");
         policy.SupportsCredentials = true;
    
         services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy));
    

    .NET 4.6

    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*", SupportsCredentials = true)]
    

    【讨论】:

    • 感谢您的评论,但遗憾的是......不,这不是 cors 政策,因为我已经这样配置了。我现在更新了我的问题
    • 做了一些改变,你能不能试着像这样添加SupportsCredentials ..实际上我在.NET 4.6中实现了同样的事情,而不是核心
    • 我的库中没有 Microsoft.AspNet,只有 AspNetCore。另外我认为 AllowCredentials() 和 SupportCredentials 是相同的,只是 .NET 版本不同。也许问题是服务器和客户端都在VPN下。
    • 嗯..可能是..希望你找到解决方案:)
    猜你喜欢
    • 2018-01-23
    • 2018-07-09
    • 2023-03-18
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多