ASP.NET – Get User Name Under Windows Authentication

ASP.netGetting the authenticated user’s name when using Windows Authentication with ASP.NET is very simple.  I just keep having to go back to Google or dig out an old project to remember it, so here it is:

string username = User.Identity.Name.ToString();

Be sure to add the Security reference:

using System.Web.Security;

Thats it!

[UPDATE] Check out the comments below for some additional suggestions on getting the user name without the Domain name.

Byron

7 Responses to “ASP.NET – Get User Name Under Windows Authentication”

  1. Brian June 26, 2009 at 12:18 pm #

    Thanks for the help above though

    The above code returns the whole name including the computer name
    eg
    when i write those codes to my computer i gives me the following result

    BROMPO-379477BA\Brian

    But i just want to get Brian and not the whole string how will i do that???

  2. Byron Bennett June 28, 2009 at 12:20 am #

    Brain,
    I’m not sure. I was getting the domain name when I was using it since I was on a LAN with Active Directory running. Since the domain was always the same for my app, I checked for it and replaced it. Sorry I don’t have the answer right now.

    BB

  3. Thang July 3, 2009 at 3:15 am #

    Hi Brian,
    You try with below code
    string strAccount = HttpContext.Current.User.Identity.Name.ToString();
    string strUserName = strAccount .Split(“\\”.ToCharArray())[1];

    have fun coding,
    BB

  4. AD Guy July 9, 2009 at 1:24 am #

    DirectoryEntry dEntry = new DirectoryEntry(“WinNT://” + Environment.UserDomainName + “/” + Environment.UserName);
    return dEntry.Properties["fullName"].Value.ToString();

  5. Byron Bennett July 9, 2009 at 7:24 am #

    @Thang, @AD Guy,

    Thanks for the hints!
    Byron

  6. Chuck December 14, 2009 at 3:05 pm #

    Even easier to get the AD user name

    my.user.name

  7. Seth April 8, 2010 at 1:07 pm #

    The only consistent solution was AD Guys as we use Form Authentication in our project and none of the others would pull the information but that one. We have a need for a seperate part of our application to pull AD Information but sill need Forms Authentication for others and that solution was the only one that worked.

    Thanks AD Guy.