Windows Authentication with asp.net core

2019-01-23 08:09发布

问题:

Please provide guidance on how to implement Windows Authentication on ASP.NET Core RC2+.

I see other SO questions that describe bearer authentication like Bearer Authentication with ASP.NET Core RC2 404 instead of 403

But that is not what I am looking for.

回答1:

You can do this using WebListener, like so:

  1. Open your project.json and add WebListener to dependencies:

    "dependencies" : {
      ...
      "Microsoft.AspNetCore.Server.WebListener": "0.1.0-rc2-final"
      ...
    }
    
  2. Add WebListener to commands (again in Project.json)

      "commands": {
        "weblistener": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener"
      },
    
  3. In Startup.cs, specify the WebHostBuilder to use WebListener with NTLM

     var host = new WebHostBuilder()
            // Some configuration
            .UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
            // Also UseUrls() is mandatory if no configuration is used
            .Build();
    

That's it!



回答2:

This doesn't appear to work any longer in the .Net Core 1.0.0 (RTM). I do the WebHostBuilder exactly as above in Ivan Prodanov's answer; it runs, don't get an error there, but the HttpContext.User is not marked with a WindowsIdentity. Following code used to work in ASP.Net 5 beta6:

in project.json:

"version": "1.0.0"
"dependencies": {
  "Microsoft.AspNetCore.Owin": "1.0.0",
  "Microsoft.AspNetCore.Server.WebListener": "0.1.0",

in middleware class:

public async Task Invoke(HttpContext context)
{
    try
    {
        ClaimsPrincipal principal = context.User;

// <-- get invalidcastexception here:
        WindowsIdentity winIdentity = (WindowsIdentity)principal.Identity;  

        ....
        ....


回答3:

Check your launchSettings.json file - change anonymousAuthentication to false

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

For deployment to iis check this Asp.Net core MVC application Windows Authentication in IIS