ASP.NET Login Authentication Problem
I was trying to create a Login page for my website in ASP.NET a couple of days ago and I was stumped that the following piece of code did not work:
private bool SiteLevelCustomAuthenticationMethod(string User, string Password)
{
bool boolReturnValue = false;
DataTable dtAuthUsers = SomeBLL.GetUsers();
if (dtAuthUsers != null && dtAuthUsers.Rows.Count > 0)
{
DataView dvAuthUsers = dtAuthUsers.DefaultView;
foreach (DataRowView drvAuthUsers in dvAuthUsers)
{
if (User == drvAuthUsers.Row["User"].ToString() && Password == drvAuthUsers.Row["Password"].ToString())
{
boolReturnValue = true;
}
}
}
return boolReturnValue;
}
protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
{
bool Authenticated = false;
Authenticated = SiteLevelCustomAuthenticationMethod(LoginControl.UserName, LoginControl.Password);
e.Authenticated = Authenticated;
if (Authenticated == true)
{
FormsAuthentication.RedirectFromLoginPage(string.Format("{0}", LoginControl.UserName), false);
}
}
Now after numerous debug sessions on this code, I could not find a thing wrong with it. The correct Username and Password was getting parsed to the Database but still the 'SiteLevelCustomAuthenticationMethod' function was still returning a false.
What was causing this problem was actually quite simple (even though it had taken my a long time to solve!). Basically, in the User's table in my database had the following columns:
- User_ID ------> DataType: int
- Username ------> DataType: nvarchar
- Password ------> DataType: char
Now this table look alright doesn't it? Well it isn't. The problem lies within the 'Password' column. Since this column format is 'char' with a length of 25, when you enter a password that is less than 25 characters in length a space will be added after to fill out the data length. For example, if you had a password that was 10 characters long, an extra 15 characters of spacing will be added after your password.
In order to fix this problem, I changed the Password DataType to 'nvarchar', which solved the problem.