显示用户名或密码是否错误?

时间:2018-12-21 08:54:42

标签: c# login

描述并显示usernamepassword是不正确的

我当前的代码:

public partial class Form1 : Form
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\AKO Cc\Desktop\visual\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf;Integrated Security=True");

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlCommand sql=new SqlCommand("select * from db where username='"+textBox1.Text+"' and password='"+textBox2.Text+"'",con);
        SqlDataReader rs=sql.ExecuteReader();
        if (rs.HasRows) {
            rs.Read();
            string id = rs.GetValue(0).ToString();
            string type = rs.GetValue(3).ToString();
            MessageBox.Show(id + " " + type);
        }
        rs.Close();
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:2)

首先,您有一个易受攻击的设计:db表被盗时,所有登录名/密码都会被破坏。不要存储密码,但要存储其哈希

接下来,让我们提取一种方法(单独的业务逻辑-credentail验证和 UI -TextBox es):

   // static: we don't want form's instance: "this"
   private static bool IsCredentialValid(string login, string password) {
     //TODO: do not hardcode the connection string, but load it 
     // new SqlConnection() - do not cache conections, but create them
     // using - do not forget to free resources
     using (SqlConnection con = new SqlConnection(@"...")) {
       // Make Sql readable and parametrized
       string sql = 
         @"select 1 -- we don't want to fetch any data
             from db
            where [UserName] = @UserName and
                  [Password] = @Password";

       using (SqlCommand q = new SqlCommand(sql, con)) {
         //TODO: better to specify params' types via Parameters.Add(...)
         q.Parameters.AddWithValue("@UserName", login); 
         q.Parameters.AddWithValue("@Password", password);  

         using (SqlDataReader reader = q.ExecuteReader()) {
           // Credential is valid if we have at least one record read
           return reader.Read();
         } 
       } 
     }
   }

然后您可以轻松使用它:

   private void button1_Click(object sender, EventArgs e) {
     if (IsCredentialValid(textBox1.Text, textBox2.Text)) {
       // username and password are correct 
     }
     else {
       // username or password is incorrect 
     }
   }