How does HttpContext.Current.User.Identity.Name know which usernames exist?
For windows authentication
select your project.
Press F4
Disable "Anonymous Authentication" and enable "Windows Authentication"
How does [HttpContext.Current.User] know which usernames exist or do not exist?
Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).
Up until this point, the application has no idea who you are.
Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie
. This calls FormsAuthentication.Decrypt
(This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand
, turning the cookie into a user and stuffing it into Context.User
(Reference Source).
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.