Search code examples
c#windowsasp.net-coreauthenticationiis-express

Login with Windows challenge goes in loop in ASP .Net app


I created an ASP.Net Core app with dotnet 8 for one identity service with individual user login

dotnet new mvc --auth Individual -o MyTestProject

Then I added code change for login with username and password and all worked fine.

Now I have to add Windows-based authentication also to this. After making the changes in program.cs I added the following to my login page,

<form asp-controller="Identity" asp-action="LoginWithWindows" method="get">
    <button type="submit">Login with Windows</button>
</form>

then in my IdentityController class, I added

        [HttpGet]
        [AllowAnonymous]
        public IActionResult LoginWithWindows()
        {
            var redirectUrl = Url.Action("Index", "Home");
            // Challenge the user with Windows Authentication
            return Challenge(new AuthenticationProperties { RedirectUri = redirectUrl }, NegotiateDefaults.AuthenticationScheme);
        }

But the challenge window keeps asking for the username and password again and again even after entering the correct credentials.

I have updated the iisSettings like this

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:41772",
      "sslPort": 44356
    }
  }

So how to fix this never-ending loop of Sign-in challenge?

PS: When I created an app with dotnet new webapp --auth Windows the Windows authentication worked fine without any changes in IIS.

enter image description here


Solution

  • After a few trial and error, I'm able to solve this issue. Sharing the complete IdentityController in this gist.

    The main changes are in the IdentityController.cs file, along with this I made changes in the program.cs also like below

    // Configure Authentication to use both Windows Authentication (Negotiate) and Identity with Cookie Authentication
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        // Do not set DefaultChallengeScheme here
    
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => {
        options.LoginPath = "/Identity/Signin";
    })
    .AddNegotiate();