How to get current Windows user using ASP.NET Core RC2 MVC6 and IIS7

I have an intranet site built in MVC6 using ASP.NET Core RC2. I want to get the name of the Windows user accessing the intranet site.

So, if Jim goes to the intranet site, I want the site to get "Domain \ Jim", and if Ann goes to the intranet site, I want the site to get "Domain \ Anne".

On my IIS server, only Windows authentication is enabled, anonymous authentication is disabled.

My site is configured to use Windows Authentication and disable Anonymous Authentication.

<system.web> <authentication mode="Windows" /> <authorization> <deny users="?"/> </authorization> </system.web> 

Through Debug, I can use System.Security.Principal.WindowsIdentity.GetCurrent().Name , but of course returns "IIS APPPOOL \ SiteName" on the IIS server.

I found many examples from an old version of ASP.NET using HttpContext, and I tried to inject this into my controller with the following, but the username ends in null.

 //Startup.cs services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //HomeController.cs public HomeController(IHttpContextAccessor _accessor) { string userName = _accessor.HttpContext.User.Identity.Name; } 

What is the correct way to transfer a Windows username to an intranet site in ASP.NET Core RC2 MVC6?

+6
source share
2 answers

For anyone using Windows authentication in an Intranet application that just wants to get user information, it's easier than you think.

In your controller, this string will capture the username of the current user in the form DOMAIN \ username.

 var userId = this.User.Identity.Name; 

I spent some time looking at the other answers before I realized that most of them suggested that I was implementing individual accounts for authentication against AD, and not from the Windows Authentication window.

+3
source

Using var userId = this.User.Identity.Name; worked for me. My application runs on the intranet, and all I wanted to do was get the user login ID from Windows. I did not need to store user information, as it is already stored in Active Directory.

0
source

All Articles