Reputation: 83
Could somebody help me with my problem on my log-in form?
My username registered on the database is "admin" (all are in lowercase form). However, upon logging-in with username, "admiN" (considering N is capitalized), I still get logged-in successfully.
private void btnLogin_Click(object sender, EventArgs e)
{
Account account = new Account();
if (txtUserName.Text == "" || txtPassword.Text == "")
{
MessageBox.Show("Empty Fields Detected ! Please fill up all the fields");
return;
}
if (account.Authorize(txtUserName.Text, txtPassword.Text))
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
}
//class Account
public bool Authorize(string userName, string userPassword)
{
Connection connection = new Connection();
string sql = "SELECT * FROM tbl_Account WHERE Username=@userName and Password=@userPassword";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.Parameters.AddWithValue("@userPassword", userPassword);
conn.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
Upvotes: 1
Views: 1465
Reputation: 1596
You can do what you want by doing the comparison in C# (instead of SQL) since string comparisons are case sensitive in C#:
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
var userNameFromDb = login["Username"].ToString();
var passwordFromDb = login["Password"].ToString();
conn.Close();
return userNameFromDb == userName && passwordFromDb == userPassword
}
That being said, if this is for a something more than just your personal use / learning, I would recommend you reconsider how you are storing passwords. Right now, it looks like you're storing them in clear text which is a huge security risk. You should look into hashing and salting passwords and use a pre-made framework for authorization / authentication.
Also, I agree with other commenters that probably want to ignore case for the username.
Upvotes: 0
Reputation: 472
Your query will not take case into account. (default SQL Server behavior)
SELECT * FROM tbl_Account WHERE Username=@userName and Password=@userPassword
You can change your query to
SELECT * FROM tbl_Account
WHERE Username=@userName COLLATE SQL_Latin1_General_CP1_CS_AS
AND Password=@userPassword COLLATE SQL_Latin1_General_CP1_CS_AS
By changing the collation, it will take into account the case.
Upvotes: 2