Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core WebAPI CORS with Windows Authentication

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

like image 434
Matthew Christianson Avatar asked Jul 31 '17 14:07

Matthew Christianson


People also ask

Can we use Windows authentication in Web API?

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.


1 Answers

I had the same problem. Finally got solution that worked for me. So you could try follow this pattern:

  1. Enable CORS middleware(which you've already done) by doing this:

    services.AddCors(options ={
      ...
      //describe your options here
      ...    
    });
    
  2. Enable Windows Authentication & Anonymous Authentication for IIS/IIS Express(depends what you use).

  3. 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>  
    
  4. Apply [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 property
like image 175
Eugene S. Avatar answered Oct 13 '22 14:10

Eugene S.