percival.09b
Member
I made a login with authentication in DotNet windows forms app and I'm trying to do my best to guard the database from SQL injection attacks, but it seems like there was a wrong logic in my code. Any help would be appreciated
Inside the login button function:
private void BtnLogin_Click(object sender, EventArgs e) //user login authentication
{
bool userValidated = validateUserInput(userText.Text);
bool passValidated = validateUserInput(passText.Text);
if (userValidated && passValidated)
{
getConnection();
}
try
{
NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Database=UserLogin;Username=postgres;Password=adminAd1234");
NpgsqlDataAdapter conDataAdapter = new NpgsqlDataAdapter();
//NpgsqlDataAdapter conDataAdapter = new NpgsqlDataAdapter("select * from public.tb_userlogin where username='" + userText.Text + "'and password='" + passText.Text + "'", conn);
DataTable conTable = new DataTable();
conDataAdapter.Fill(conTable);
/* -UNSAFE command-
sql = @"SELECT employee_no FROM public.tb_userlogin where
username ='" + Convert.ToString(userText.Text) + "' AND password ='" + Convert.ToString(passText.Text) + "'";
*/
string username = userText.Text;
string password = passText.Text;
conn.Open();
conDataAdapter.SelectCommand = cmd;
//cmd = new NpgsqlCommand(sql, conn);
cmd = new NpgsqlCommand("SELECT * FROM public.tb_userlogin where username = $username AND password = $password", conn);
EmpNo = code.Converter_string(sql).ToString();
cmd.Parameters.AddWithValue("$username", userText.Text);
cmd.Parameters.AddWithValue("$password", passText.Text);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (userText.Text == String.Empty || passText.Text == String.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
if (EmpNo != "0")//log in successfully
{
this.Hide();
new ClientCrudFrm().Show();
}
else
{
MessageBox.Show("Please check your username or password", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
if (conTable.Rows.Count == 1)
{
MessageBox.Show("login successfully");
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message,
"Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
conn.Close();
}
}
Last edited: