Search code examples
angular.net-corecorspreflight

PreflightMissingAllowOriginHeader CORS error on .NET Core 3.1 + Angular


I'm developing an application on .NET Core 3.1 + Angular and everything was working fine until recently, when I was trying to implement Negotiate Authentication configuration to the backend. Anyway the issue persists even after reverting all the Authentication configuration so it may not be related.

I'm getting CORS error with description PreflightMissingAllowOriginHeader followed by 401 error.

CORS error + 401

CORS error request details

Below you can see my code. Out of frustration I have even allowed all origins, headers and methods, when I was trying to debug this issue.

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials(); });
        });

// Tried both ^ and v

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

        services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

    .
    .
    .
    .
    .
    }


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

        /*            app.UseHttpsRedirection();*/

        app.UseRouting();

        app.UseCors(MyAllowSpecificOrigins);
        
        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins); // <--- Tried both with and without RequireCors
        });

    }

Angular WebReqService

readonly ROOT_URL: string;
readonly httpHeaders: HttpHeaders = new HttpHeaders({'Content-Type': 'application/json'});
readonly httpOptions = {
headers: this.httpHeaders,
withCredentials: true
};

constructor(private http: HttpClient) {
  this.ROOT_URL = 'http://localhost:5000';
}

get(uri: string): Observable<any> {
  return this.http.get<any[]>(`${this.ROOT_URL}/${uri}`, this.httpOptions);
}

The strangest about it is that if I try to access the API directly by calling the request in browser or in Insomnia with NTLM Authorization, everything works just fine. Only if I try to access the API from Angular FE, I get the error.

Any ideas what could be the cause and how to fix it? Also, I think that it's not caused by not being authorized to use the application, because as I said it works outside the Angular and also if user is not authorized, it's configured to return 403 instead of 401.


Solution

  • You can try to setup Angular proxy.

    1 - create a file proxy.conf.js at the root of your angular app with the following :

        const PROXY_CONFIG = [
         {
         context: ["/api"],
         target: "http://localhost:5000",
         secure: false,
         logLevel: "error",
         changeOrigin: true,
        }
       ];
       module.exports = PROXY_CONFIG;
    

    2 - in angular.json in projects -> yourprojectname -> architect -> serve ->configurations -> development, add "proxyConfig": "proxy.conf.js"

     "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "configurations": {
                "production": {
                  "browserTarget": "client:build:production"
                },
                "development": {
                  "browserTarget": "client:build:development",
                  "proxyConfig": "proxy.conf.js"
                }
              },
    

    3 - in your Angular WebReqService, set this.ROOT_URL = 'http://localhost:4200';