0

I have an application for an organization where a user will logged in to his system with domain user, so now I want to get that logged in user. I tried many methods and get username locally, but my application is on IIS and it gets the IIS user with IIS APPPool\DefaultAppPool while system name and domain get but username not.

This is the code I am using for getting username:

Request.ServerVariables.Get("logon_user");
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Environment.GetEnvironmentVariable("USERNAME");
System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;

If someone knows how to get local username rather than IIS, please share. Thanks in advance.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • Is your application configured to use windows authentication? – Chetan Dec 31 '21 at 07:47
  • i enabled windows authentication to true in webconfig and in iis setting but still not working. – Tauseef Ahmad Dec 31 '21 at 08:10
  • @chetan i want to show current logged in username of domain of local system on login screen and display a message to user that you logged in from your computer with this user do you want to login if yes than it will auto login , for auto login i will first check that user with our database , but first i want to get that username of local system. – Tauseef Ahmad Dec 31 '21 at 08:15
  • Try accessing Request.User – Chetan Dec 31 '21 at 08:15
  • Web application runs on web server and user accesses it on client machine via browser. So web application can not access the currently logged in users details from client machine just like that in c# code. – Chetan Dec 31 '21 at 08:20
  • https://stackoverflow.com/questions/16184685/how-do-i-get-the-currently-loggedin-windows-account-from-an-asp-net-page – Chetan Dec 31 '21 at 08:24
  • https://blog.bitscry.com/2020/05/05/getting-the-windows-user-name-in-asp-net-core/ – Chetan Dec 31 '21 at 08:25
  • but it gives machine name and active directory domain name and how to skip or tell iis to get local machine user. and how to access Request.User – Tauseef Ahmad Dec 31 '21 at 08:29
  • Did you get a chance to go thru the links I shared? You can get domain name because server is part of the domain name. So it gets the domain name of the server not the client. – Chetan Dec 31 '21 at 08:38
  • https://blog.lextudio.com/miseries-around-asp-net-windows-authentication-setup-14e2e8522ad2 There are framework specific `.User` properties for you to access. – Lex Li Jan 01 '22 at 02:26

1 Answers1

0

If you have Windows Authentication working, then the current user is available in HttpContext.User.

User.Identity.Name will be the username.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84