1

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?

1
  • This is problem with CORS not with Angular. Error is clear, you need to implement "Access-Control-Allow-Origin" header on the backend side. Reason of CORS in your case is different ports of apps (client and server). PS. Make sure you allow OPTIONS request, it is necessary to make CORS works. Commented Mar 20, 2019 at 15:23

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

what if I don't want to enable anonymousAuthentication? Isn't there another way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.