I have an asp.net application. In which i have this code:
using (Data.connexion) { string queryString = @"select id_user , nom, prenom, mail, login, mdp, last_visite, id_group, id_user_status from USERS where login =@login and mdp=@mdp"; SqlCommand command = new SqlCommand(queryString, Data.connexion); command.Parameters.AddWithValue("@login", _login); command.Parameters.AddWithValue("@mdp", _password.GetHashCode().ToString()); try { SqlDataReader reader = command.ExecuteReader(); do { while (reader.Read()) { return View("Success"); } } while (reader.NextResult()); } catch { } } When i try a Sql injection attack using this login '' or 1=1 -- , the attack is failed. but if i change the snippet by this one :
using (Data.connexion) { string queryString = @"select id_user , nom, prenom, mail, login, mdp, last_visite, id_group, id_user_status from USERS where login =" + _login + " and mdp=" + _password.GetHashCode().ToString(); SqlCommand command = new SqlCommand(queryString, Data.connexion); // command.Parameters.AddWithValue("@login", _login); // command.Parameters.AddWithValue("@mdp", _password.GetHashCode().ToString()); try { SqlDataReader reader = command.ExecuteReader(); do { while (reader.Read()) { return View("Success"); } } while (reader.NextResult()); } catch { } } I'm redirected to the view success so the attack is succed.
What is the difference between the two ways of coding? What are the best ways to prevent and avoid an Sql injection attack?