我正在设计一个网站,用户在该网站上指定一个帐户ID(必须是8位数字),以便查找与该帐户关联的帐单日期。我使用了asp.net regex验证器来阻止用户输入字符。我还在此文本框中附加了必填字段验证器。
我已经阅读过其他stackoverflow问题的SQL注入攻击,但我没有遇到任何与使用验证器保护查询相关的问题。
设置这些验证器后,我有理由担心sql注入攻击吗?我还需要(或应该)做些什么来防止恶意用户滥用这个用户输入。
以下是SQL查询的C#代码,并使用与AccountID关联的帐单周期日期填充下拉列表:
string sqlCommandString = "SELECT StatementDate AS StateDate FROM dbTable " +
"WHERE AccountID = '" + AccountID + "' ORDER BY StatementDate DESC";
string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
{
sqlConnection.Open();
DropDownList_StatementDate.DataSource = sqlCommand.ExecuteReader();
DropDownList_StatementDate.DataBind();
}
这是我使用的正则表达式验证器:
<asp:RegularExpressionValidator
ID="RegExpVal_AccountID"
runat="server"
ErrorMessage="Must be 8 digits"
ValidationExpression="^\d{8}$"
ControlToValidate="TextBox_AccountID"
CssClass="ValidatorStyle"
Display="Dynamic">
</asp:RegularExpressionValidator>
谢谢。
答案 0 :(得分:11)
只需使用参数化查询(防止SQL注入攻击的唯一安全方法):
string sqlCommandString = "SELECT StatementDate AS StateDate FROM dbTable " +
"WHERE AccountID = @AccountID ORDER BY StatementDate DESC";
string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
{
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("@AccountID", AccountID);
DropDownList_StatementDate.DataSource = sqlCommand.ExecuteReader();
DropDownList_StatementDate.DataBind();
}