I have a .Net Core WebAPI service for which I have enabled CORS (with the code below), in the properties of the project I have disabled anonymous authentication and enabled Windows authentication. The POST and PUT endpoints work with anonymous auth enabled but fail when its disabled. 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 });
}
Has anyone got any experience of this?
Thanks
Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.
I had the same problem. Finally got solution that worked for me. So you could try follow this pattern:
Enable CORS middleware(which you've already done) by doing this:
services.AddCors(options ={
...
//describe your options here
...
});
Enable Windows Authentication & Anonymous Authentication for IIS/IIS Express(depends what you use).
Add web.config to your project's root folder with forwardWindowsAuthToken="true"
flag. 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>
[Authorize]
attribute to your controllers/actions. And that's it. Now you're able to send POST & PUT requests as well as get user's identity simply by accessing User.Identity.Name
propertyIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With