string sql = "SELECT * FROM tblUser WHERE Name = '" + txtName.Text +
"' AND Password = '" + txtpassword.Text + "'";
Well, the above statement looks fine but what a malicious user would now do is add condition such as
So that the actual SQL statement becomes
The double dashes comment out rest of the statement and the condition 3=3 is added. Since 3 is always equal to 3 the query selects every row in the table thus giving access to information which wouldn't be available otherwise.
However, parameterizing the SQL statement would not only remove this vulnerability but also enhance performance multifold. Parameterized SQL statements are in some ways similar to stored procedures, so if you have worked with the latter, the concept of parameterized query would be easier to understand. Further, since the parts of the SQL statement are added as parameters, the same code can be reused.
Now let us create a parameterized SQL statement in ASP.NET. As usual, we would be required to first create our connection and command objects. We would then add parameters to it before it is executed.
SqlConnection objCon = new SqlConnection(ConnectionString);
objCon.Open();
SqlCommand objCommand = new SqlCommand(
"SELECT * FROM User WHERE Name = @Name AND Password = @Password",
objConnection);
objCommand.Parameters.Add("@Name", txtName.Text);
objCommand.Parameters.Add("@Password", txtpassword.Text);
SqlDataReader objReader = objCommand.ExecuteReader();
if (objReader.Read())
{
----------
--------
---------
}