Here is the code in question:<p><pre><code> protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = @"Data Source=OFFICE7-PC\SQLEXPRESS;Integrated Security=True";
string sqlQuery = "Select UserName From [Users].[dbo].[UsersInfo] Where UserName = ' " + TextBox1.Text + "' and Password = ' " + TextBox2.Text+"'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
}
}
finally
{
if (reader.HasRows)
{
reader.Close();
Response.Redirect(string.Format("WebForm2.aspx?UserName={0}&Password={1}", TextBox1.Text, TextBox2.Text));
}
else
{
reader.Close();
Label1.Text = "Wrong user or password";
}
}
}
}
</code></pre>
In my opinion, this is what needs to be changed:<p>-"Button1" should be given a more descriptive name. We can easily see from the query that it's getting a list of users, but would it really kill to take the time to give it a better name like "btnGetUsers?"<p>-The query string should REALLY be put into the web.config file, or heaven help us all at least as a private readonly at the top of the class containing this method.<p>-Is this query trying to get the username based on what username and password is entered? It looks like the coder is trying to do authentication based on the number of rows returned.. or at least <i>tried</i> to.
-The query is also VERY badly written; it's entirely prone to SQL injection.<p>-He gets one point for at least making use of the "using" construct to make sure the SqlConnection gets disposed of once done!<p>-That "try" block with the while loop is a big WTF for me. Why is it waiting? It will always time out no matter what.<p>-What is the point of the redirection to WebForm2? If the user gets the login right, then hooray, they're on the site, but otherwise the password is wrong. Still, what's to stop anyone from just bypassing this whole thing by just messing with the URL parameters?