How to: Display the name of the Windows user logged into your ASP.NET Site

This article is reposted from my old MSDN blog. Please post comments here as I am no longer able to publish or respond to them on MSDN. Thanks!

This is really pretty simple but I was surprised not to find it in any one blog posting. The following code retrieves the display name of the logged in user, such as “Bob German” (not “domain\username”). It’s easy to accidentally display the Application Pool account rather than the logged in user. Some articles said to turn on Impersonation, but that’s often a bad idea for other reasons. This is what worked for me just now:

string username = "";
IPrincipal userIdentity = HttpContext.Current.User;
PrincipalContext context =
    new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal =
    UserPrincipal.FindByIdentity
        (context, userIdentity.Identity.Name);
if (userPrincipal != null)
{
    username = userPrincipal.DisplayName;
}

I hope this helps someone; thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s