C# 在 asp.net 中的数据库中验证用户名和密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16533088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating username and password in a database in asp.net
提问by yrazlik
I am trying to create a login page. I have a database table called Login, and it has two columns: ID and Password. It has the following ID and Password pairs in it: First row:(13282,123456), Second Row:(11111,11111). If username and password is right, i redirect page to succesful.aspx, if either username or password is wrong, i redirect page to unsuccesful.aspx. My problem is, When i enter 13283 as ID and 123456 as password, it does everything right, i am redirected to succesful page. But when i enter ID=11111 and Password=11111 even though everything is true, it redirects to unsuccesful page. I think the problem is, my query only checks the first row. Here is the code:
我正在尝试创建一个登录页面。我有一个名为 Login 的数据库表,它有两列:ID 和密码。它包含以下 ID 和密码对:第一行:(13282,123456),第二行:(11111,11111)。如果用户名和密码正确,我将页面重定向到 succesful.aspx,如果用户名或密码错误,我将页面重定向到 unsuccesful.aspx。我的问题是,当我输入 13283 作为 ID 和 123456 作为密码时,它一切正常,我被重定向到成功页面。但是当我输入 ID=11111 和 Password=11111 时,即使一切都是真的,它会重定向到不成功的页面。我认为问题是,我的查询只检查第一行。这是代码:
protected void loginButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=University;Integrated Security=True;Pooling=False";
Int32 verify;
string query1 = "Select count(*) from Login where ID='" + idBox.Text + "' and Password='" + passwordBox.Text + "' ";
SqlCommand cmd1 = new SqlCommand(query1, con);
con.Open();
verify = Convert.ToInt32(cmd1.ExecuteScalar());
con.Close();
if (verify > 0)
{
Response.Redirect("succesful.aspx");
}
else
{
Response.Redirect("unsuccesful.aspx",true);
}
}
采纳答案by dasblinkenlight
Several things are wrong with this approach:
这种方法有几个问题:
- It requires storing passwords in plain text- This is the worst thing one can do to a user's password: anyone who accidentally gains access to your database would instantly be in possession of all your users' passwords, with is very, very bad.
- It is susceptible to SQL Injection attacks- Concatenating strings to produce a SQL command is dangerous, because malicious users could enter strings that break your SQL and turn it into something else.
- 它需要以纯文本形式存储密码——这是对用户密码所做的最糟糕的事情:任何意外获得对您数据库的访问权限的人都会立即拥有您所有用户的密码,这是非常非常糟糕的。
- 它容易受到 SQL 注入攻击- 连接字符串以生成 SQL 命令是危险的,因为恶意用户可能会输入破坏 SQL 的字符串并将其转换为其他内容。
You should study the answers to this question. The approaches discussed there are not nearly as simple as what you are implementing, but they make your system a lot more bullet-proof.
你应该研究这个问题的答案。那里讨论的方法并不像您正在实施的方法那么简单,但它们使您的系统更加防弹。

