Search code examples
c#sqlparameterssql-injectionsqlparameter

c# Is this a safe way for a login form?


                myConnection.Open();
            myString = textBox2.Text;
            myPass = textBox1.Text;
            MessageBox.Show("Connection established!", "Succes!", MessageBoxButtons.OK);
            using (MySqlCommand looking = new MySqlCommand("Select * FROM `users` WHERE username LIKE @User AND password LIKE @password", myConnection))
            {
                looking.Parameters.Add(new MySqlParameter("User", myString));
                looking.Parameters.Add(new MySqlParameter("password", myPass));
                MySqlDataReader readData = looking.ExecuteReader(); 

                while(readData.Read()) 
                {
                    login = true;
                }
if (login)
   MessageBox.Show("Succes!");
}

Hi! I wonder if the code above is a safe way for a login form? Is it possible to do a SQL injection here?

Also how do I save my connectionstring safely? I've been looking around but I don't know the best option..


Solution

  • It is safe for SQL Injection, but you should compare for exact match instead of using LIKE for username and password.

    "Select * FROM `users` WHERE username = @User AND password = @password"
    

    Apart from safety, if you are only interested in knowing if the records exists or not, then use COUNT and get the results using ExecuteScalar instead of select all the columns.

    "Select COUNT(*) FROM `users` WHERE username = @User AND password = @password"
    

    and get the results as:

    int count = (int) looking.ExecuteScalar();
    if(count > 0)
    {
       //found
    }