.Net Core WebAPI CORS with Windows Authentication
I have a .Net Core WebAPI service for which I have CORS enabled (with the code below), in the project properties I have disabled anonymous authentication and enabled Windows authentication. POST and PUT endpoints work with anonymous authorization but fail when disconnected. I get
OPTIONS http://localhost:64113/api/ 401 (Unauthorized)
Code to enable CORS
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
Angular code
public XXX(data: any): Observable<Response> {
return this.http.put(this.baseUrl, data,
{ withCredentials: true });
}
Anyone have any experience?
thank
source to share
I had the same problem. Finally I got a solution that worked for me. Therefore, you can try following this pattern:
-
Enable CORS middleware (which you already did):
services.AddCors(options ={ ... //describe your options here ... });
-
Enable Windows Authentication and Anonymous Authentication for IIS / IIS Express (Depends on what you are using).
-
Add web.config to your root project folder with flag
forwardWindowsAuthToken="true"
. In my example, it looks like this:<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <remove name="aspNetCore"/> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/> </handlers> <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true"/> </system.webServer> </configuration>
- Apply attribute
[Authorize]
to your controllers / actions. And so it is. Now you can send POST and PUT requests and also get user identity simply by accessingUser.Identity.Name
property
source to share