Search code examples
angularcorsasp.net-core-webapiwindows-authentication

could not post to asp.net core web api using windows authentication


The api is AspNetCore WebApi with default configuration for Windows authentication and CORS enabled. The client is Angular with GET and POST methods.

The GET call is successful:

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

The POST is failed:

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

02 exceptions are

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

and

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.

Any idea please?


Solution

  • The POST causes the browser to send OPTIONS to the web api before real POST. However the webapi rejects this call because the configuration is based on Windows authentication only. The solution is to enable both Windows authentication for controllers as well as anonymous authentication for OPTIONS in launchSetting.json.

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

    and add 1 line before AddMvc in Startup.cs

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