ASP.NET Login Authentication Problem

Published on
-
1 min read

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:

  1. User_ID ------> DataType: int
  2. Username ------> DataType: nvarchar
  3. 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.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.