LilRazi
LilRazi

Reputation: 770

Preflight (Option) request is failing after enabling Windows Authentication in Angular 9 + Asp.net Core Web API

We have asp.net core web api and angular 9 application. Asp.net core web API has windows authentication enabled using below code. Also, for testing I am enabling the CORS for all.

"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");

When I am making a GET request I am getting the response but when making a POST request it is failing. I have already set withCrendtial set to true. Below is the interceptor where I am setting this

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

Also, registering the interceptor on app module like this

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

Access to XMLHttpRequest at 'https://localhost:44305/anotherdata/test' 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.

Upvotes: 1

Views: 381

Answers (1)

Robin Webb
Robin Webb

Reputation: 1521

I'm using .NET Core 3.1 and this is how my "API" project looks. This is all I need to get CORS to working Startup.cs. **Need to restart IIS express server to pick up changes.

 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(); });
        }


Upvotes: 1

Related Questions