I recently discovered some unexpected behavior when using the Login Control provided by ASP.NET in combination with forms authentication.
The task was to create unique logins to provide access to an internet-based web application via forms authentication. After successful login user-related data should be listed in a grid based on a user-specific query. Due to the uniqueness of the generated login names, I decided to use the login name instead of the user key as part of the Where-clause in the SQL-query to fetch the data. The login name was extracted from the Page Property User.Identity.Name after successful authentication.
After deployment some users copied and pasted their credentials given by invitation mails into the login control of the login page. This had in some cases the effect that leading blanks were pasted togehter with the login name into the control.
Well, leading blanks are not an issue in order to successfully authenticate via the login control. Obviously the login control trims the login name before the actual authentication happens which is not a bad thing.
The bad thing is that it sets the Page.User.Identity.Name Property with the login name and the leading blanks. So the query failed and the grid was empty.
It took a while to track down this behavior because it is difficult to recognize a leading blank in the log files.
So here are the options:
A) stay on the safe side and use the GetUser-Function of the Membership class:
MembershipUser mu = Membership.GetUser(User.Identity.Name);
string strUserName = mu.UserName;
B) of course, always trim your extracted user name:
string strUserName = Page.User.Identity.Name.Trim();