User.Identity.Name is empty in Asp.NET Core 2.0 API Controller
I've also been having this problem with ASP.Net Core 2, and I'm really surprised no one's discovered the other cause of this problem.
When my webapp is deployed to IIS, "User.Identity.Name
" always returns null. The IIS site has anonymous access disabled, and windows authentication is enabled.
BUT.
I didn't realise that my ASP.Net Core 2 has a "launchSettings.json
" file, quietly hidden under the Properties
folder, and in there, there's also some iisSettings, and in here "windowsAuthentication
" was, strangely, set as false by default.
Changing "windowsAuthentication
" to true, and "anonymousAuthentication
" to false solved the problem for me.
After doing this, "User.Identity.Name
" did finally contain the correct username.
But what the heck is this setting ? Why would this get priority over the actual settings we've setup in IIS Manager ?!
Yes, you need to specify the claim for the unique name which is translated into the user.identity.name:
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)