How do I get the currently loggedin Windows account from an ASP.NET page?
Asked Answered
P

9

24

I have an ASP.NET 3.5 application that uses ASP.NET forms authentication. I want to be able to get the Windows user name currently logged into the computer (NOT logged into the ASP.NET application, but into Windows) when data is edited in a page.

If I use Context.User.Identity.Name.Tostring(), I get the user name logged into the ASP.NET application, but I need the Windows account name.

System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring()

Also, it only works when I run the website from Visual Studio, but after deploying to IIS it returns NT AUTHORITY\SYSTEM.

Pluralism answered 24/4, 2013 at 6:17 Comment(3)
Use Windows authentication. Otherwise how will the browser know, and why would it send to the server, what Windows user is logged in?Thrasher
@CodeCaster, should i take it its completely impossible using forms authentication?. The applications uses roles for controlling access levels but i would like to get current windows account for some back end auditiongPluralism
Roles are not bound to a specific authentication method, you can use them with Windows authentication as well. Is this an intranet application?Thrasher
W
18

You have to set authentication mode to Windows in your configuration & also disable anonymous users in authorization tag.

Wrecker answered 24/4, 2013 at 6:26 Comment(2)
Hi,i have two modules in same project i.e client and admin module.Client website has login page and admin module use windowsAuth mode..if i set the mode in .config then will it effect the client module?Guillotine
How do I disable anonymous users in authorization tag?Liger
L
11

To get the currently logged in user to a Windows account you have to use Windows authentication instead of Forms authentication:

System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring() also only works when i run the website from visual studio but after deploying to IIS it returns NT AUTHORITY\SYSTEM

It shows the application current user. When you host your application on the Visual Studio web server it uses your local account. However, when you will log in to the web application with different credentials it will always show your current Windows login.

An application deployed to IIS uses the NT AUTHORITY\SYSTEM account in your case.

Lingle answered 24/4, 2013 at 6:24 Comment(0)
I
9

To get the currently logged-in user to Windows in C#, use:

string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Iden answered 29/3, 2016 at 12:23 Comment(0)
V
9

I struggled and struggled and struggled with this. One of the things is that I don't have access to IIS, that is locked down, so I couldn't change any of the server settings. I had to go with what I was capable of doing in code. When I researched it, many of the replies said, "set up IIS like this". . .well, that's great when you have access to IIS, but I didn't -- I had to work with what I could do in code. So, I ended up handling it like this:

In my web config file, I added the following lines of code within the section:

<system.webServer>
<security>
  <authentication>
    <anonymousAuthentication enabled="false" />
    <windowsAuthentication enabled="true" />
  </authentication>
</security>
</system.webServer>

Then, it returned an error on my local, which I had to go in and fix. I went to the applicationhost.config file located in the following path on my machine (yours might be different):

C:\users\"your user name"\My Documents\"yourIISInstallation"\config\applicationhost.config

and I changed the following settings to "allow", which had been set to "deny":

<section name="anonymousAuthentication" overrideModeDefault="Deny" />

changed to

<section name="anonymousAuthentication" overrideModeDefault="Allow" />

and

<section name="windowsAuthentication" overrideModeDefault="Deny" />

to

<section name="windowsAuthentication" overrideModeDefault="Allow" />

in the

<sectionGroup name="authentication">

section. Before I found out this fix, I was pulling my hair out over this. I hope this helps someone. As soon as I put in the above code into the webconfig file, it worked on the intranet, it just returned errors in my local, but as soon as I added the above to my local applicationhost.config file, it started working on my local as well. Then, I called the following variable to return the name of the logged in user on windows:

    HttpContext.Current.User.Identity.Name.ToString().Substring((HttpContext.Current.User.Identity.Name.ToString().IndexOf("\\")) + 1);

Cheers!

Vasty answered 7/8, 2017 at 18:9 Comment(0)
G
4

I use this:

System.Security.Principal.WindowsPrincipal user;
user = new WindowsPrincipal(this.Request.LogonUserIdentity);
this.Request.LogonUserIdentity.Impersonate();
user_name = user_name.Substring(user_name.LastIndexOf("\\") + 1);
Graupel answered 24/4, 2013 at 6:27 Comment(1)
Is this still getting the current logon windows authentication in computer when it is deployed in IIS? And there's no need for authentication=windows in web config?Sciolism
C
1
string strName = HttpContext.Current.User.Identity.Name.ToString();

like you wanted it to do was correct, but you need to set up the webserver first, referring to How to Get Window NT Logged User Name Using ASP.NET (first steps setting up a web server).

Cricoid answered 24/4, 2013 at 6:19 Comment(0)
T
0

Try with the below line of code:

string loggedOnUser = string.Empty;
 loggedOnUser = Request.ServerVariables.Get("AUTH_USER");

You may not be getting the values when you run the application from Visual Studio... Check it after deployed in IIS.

For getting the User name, use:

string userName = string.Empty;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "Your Domain Name"))
{
    UserPrincipal user = new UserPrincipal(pc);
    user = UserPrincipal.FindByIdentity(pc, "User ID Will Come here");
    if (user != null)
    {
        userName = user.GivenName + " " + user.Surname;

    }
    else
    {
        //return string.Empty;
        userName = "User Not Found";
    }
}
Trichoid answered 24/4, 2013 at 6:24 Comment(0)
S
0

I managed to resolve this issue by following the instructions on here in Method 1 at the following link - https://support.microsoft.com/en-us/help/896861/you-receive-error-401-1-when-you-browse-a-web-site-that-uses-integrate In brief, Disable all Authentication methods except Windows Authentication. Open regedit under an admin account, locate HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0, right click the node and go New, and select Multi-String Value. Enter "BackConnectionHostNames" and click Enter. For Value enter the website you're trying to set access on and click OK. Restart IIS Once I'd done that I was able to get the current windows user using HttpContext.Current.User.Identity.Name, WindowsPrincipal(this.Request.LogonUserIdentity) also got me the Windows username logged in. For reference System.Environment.UserName and System.Security.Principal.WindowsIdentity.GetCurrent().Name, both of these still gave the IIS user.

This has taken me ages to get to the bottom of. Good luck with it. IIS is a waking nightmare!

Sussex answered 11/6, 2018 at 8:43 Comment(0)
O
0

In my case I was using

Principal.WindowsIdentity.GetCurrent().Name.Tostring()

When I went to go publish my project into IIS Manager the User ID being returned was "IIS APPPOOL\AppName". After hours of searching for a certain line of code to fix the issue it turns out it wasn't my code. Instead it was with IIS Manager itself.

The fix for me was having to Disable the "Anonymous Authentication" in the features view of IIS Manager. Shown in screenshot below.

[Navigate To Authentication][1] [1]: https://i.sstatic.net/5K8pwxHO.png

Incase Image breaks navigate like this:

IIS Manager > Your project > Features View (bottom left corner) > Authentication

The following code worked for this solution.

litUserId.Text = HttpContext.Current.User.Identity.Name.ToString();
litUserId.Text = Environment.UserName;
litUserId.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
litUserId.Text = System.Security.Principal.WindowsPrincipal user;
litUserId.Text = user.Identities.First().Name
user = new WindowsPrincipal(this.Request.LogonUserIdentity);

I hope this helps to anyone who may be out there still struggling with this.

Obvious answered 27/6, 2024 at 18:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.