Search code examples
c#asp.nethttpcontext

How does HttpContext.Current.User.Identity.Name know which usernames exist?


This is not necessarily an issue, I am just curious as to how it works. I have a method:

public static bool UserIsAuthenticated()
{
    bool isAuthed = false;
    try
    {
        if (HttpContext.Current.User.Identity.Name != null)
        {
            if (HttpContext.Current.User.Identity.Name.Length != 0)
            {
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                FormsAuthenticationTicket ticket = id.Ticket;
                isAuthed = true;
                string MyUserData = ticket.UserData;
            }
        }
    }
    catch { } // not authed
    return isAuthed;
}

The HttpContext.Current.User.Identity.Name returns null if the user does not exist, but how does it know which usernames exist or do not exist?


Solution

  • The HttpContext.Current.User.Identity.Name returns null

    This depends on whether the authentication mode is set to Forms or Windows in your web.config file.

    For example, if I write the authentication like this:

    <authentication mode="Forms"/>
    

    Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:

    <authentication mode="Windows"/>
    

    I can run the application again and check for the username, and I will get the username successfully.

    For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.