我有以下身份验证方法:
protected void Button1_Click(object sender, EventArgs e)
{
string s;
s = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(s);
con.Open();
string sqlCmd;
sqlCmd = "SELECT Username, UserPassword FROM Benutzer WHERE Username = @Username AND UserPassword =@Password";
SqlCommand cmd = new SqlCommand(sqlCmd, con);
String username = tbUsername.Text.Replace("'", "''");
String password = tbPassword.Text.Replace("'", "''");
cmd.Parameters.AddWithValue("Username", username);
cmd.Parameters.AddWithValue("Password", password);
string CurrentName;
CurrentName = (string)cmd.ExecuteScalar();
if (CurrentName != null)
{
Session["UserAuthentication"] = cmd.Parameters[0].ToString();
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "Benuztername/Password ungültig!";
}
}
这足以防止sql注入吗?我以前只是将用户名和密码直接输入到命令中,如下所示:
sqlCmd = "SELECT Username, UserPassword FROM Benutzer WHERE Username ='" + username + "' AND UserPassword ='" + pwd + "'";
其中 username 和 pwd 仅在其中存储用户名和密码文本框内容的字符串变量...
编辑:
好的,我已经编辑了我的代码,现在看起来像这样:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlDataAdapter objda = new SqlDataAdapter("[MembershipPruefen]", objcon);
objda.SelectCommand.CommandType = CommandType.StoredProcedure;
objda.SelectCommand.Parameters.Add("@Username", SqlDbType.VarChar).Value = tbUsername.Text;
objda.SelectCommand.Parameters.Add("@UserPassword", SqlDbType.VarChar).Value = tbPassword.Text;
objcon.Open();
string CurrentName;
CurrentName = (string)objda.SelectCommand.ExecuteScalar();
if (CurrentName != null)
{
Session["UserAuthentication"] = tbUsername.Text;
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "Benuztername/Password ungültig!";
}
objcon.Close();
}
这是我的存储过程:
CREATE PROCEDURE MembershipPruefen (@Username VARCHAR(50), @UserPassword VARCHAR(50))
AS
SELECT Username, UserPassword FROM Benutzer WHERE Username LIKE @Username AND UserPassword LIKE @UserPassword;
这足够了吗?我的 Web 应用程序会不会受到 sql 感染的影响,或者还有什么事情要做吗?