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?
It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.
The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
For windows authentication
select your project.
Press F4
Disable "Anonymous Authentication" and enable "Windows Authentication"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With