【问题标题】:Preflight (Option) request is failing after enabling Windows Authentication in Angular 9 + Asp.net Core Web API在 Angular 9 + Asp.net Core Web API 中启用 Windows 身份验证后,预检(选项)请求失败
【发布时间】:2020-09-02 14:31:34
【问题描述】:

我们有 asp.net core web api 和 angular 9 应用程序。 Asp.net 核心 Web API 使用以下代码启用了 Windows 身份验证。另外,为了测试,我为所有人启用了 CORS。

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:44305",
      "sslPort": 0
    }
  },


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


app.UseCors("CustomCorsPolicy");

当我发出 GET 请求时,我得到了响应,但发出 POST 请求时却失败了。我已经将 withCrendtial 设置为 true。下面是我设置的拦截器

  intercept(httpreq: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
      httpreq= httpreq.clone({
        withCredentials: true
      });
      return next.handle(httpreq);
  }

另外,像这样在应用模块上注册拦截器

{ 
  provide: HTTP_INTERCEPTORS, 
  useClass: WdAuthHttpInterceptor, 
  multi: true 
},

从源“http://localhost:4200”访问“https://localhost:44305/anotherdata/test”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

【问题讨论】:

  • 您提供的代码看起来不错。您是否在提供程序的模块中连接了拦截器,例如在 app.module.ts 中。类似 import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http';和提供者: [ // Http Interceptor(s) - 添加客户端凭据 [ { 提供:HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true } ], ],
  • 是的,我已经在app模块上注册了。
  • 一个想法。如果很明显,请道歉 - 您的拦截器在 localhost:4200localhost:8000 中。它需要在localhost:4200 中,不过我相信你已经这样做了。
  • locahost:8000 是 API,localhost:4200 是 Angular 应用程序。我在本地主机上有拦截器:4200

标签: angular webapi


【解决方案1】:

我正在使用 .NET Core 3.1,这就是我的“API”项目的外观。这就是让 CORS 运行 Startup.cs 所需的全部内容。 **需要重新启动 IIS express 服务器以获取更改。

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseCors(builder =>
                builder.WithOrigins("http://localhost:21460").AllowCredentials());

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }


【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2017-04-21
    • 2021-08-31
    • 2013-02-08
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2021-03-14
    相关资源
    最近更新 更多