C# – Windows and Anonymous Authentication in .Net Core 2.0

asp.netasp.net-coreauthenticationcnet

I'm trying to mix Windows and Anonymous authentication in a .Net Core 2.0 empty web app. I would like to avoid the [Authorize] attribute as I do not want to use Mvc or controllers.

My setup is as follows:

  1. I created an empty .Net Core 2.0 web application

  2. I went to project properties -> Debug -> Checked "Enable Windows Authentication" and disabled "Enable Anonymous Authentication".
    Now "windowsAuthentication": true and "anonymousAuthentication": false appeared in my launchSettings.json under "IIS".

  3. Inside Startup.cs, in ConfigureServices I added
    services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme); as mentioned in https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#windows-authentication-httpsys–iisintegration

  4. I added a simple Console.WriteLine(context.User.Identity.Name); to see that it works inside app.Run and…
    It all works!

However… as soon as I set "anonymousAuthentication" to true in launchSettings.json it stops working and I cannot figure out what can I do to make the Windows authentication work alongside with it. Context.User.Identity.IsAuthenticated is always false.
As you can see my configuration is very simple and I need it to stay this way. I want to enable/disable windows authentication on certain dynamic routes, so using controllers with the [Authorize] attribute is not an option.

What I'm trying to achieve is a simple app where the url "/authenticated" would reply with the value of context.User.Identity.Name and the url "/public" would reply with something like say "This is a public page!".
Something similar to NTLM authentication on specific route in ASP.NET Core but without the [Authorize] attribute and controllers.
The resources are very scarce… Anyone have any idea what I could be missing?
Thanks!

Best Answer

Anonymous takes precedence. You need to call httpContext.ChallengeAsync() when you get an anonymous request to a restricted part of your app. That will cause the client to send credentials on the next request. Here's a test that does this.