简体   繁体   English

如何使用ASP.NET和SQL Server验证用户名和密码?

[英]How to validate username and password using ASP.NET and SQL Server?

I'm trying to write an asp.net code in C# which will basically have a login page with username and pass. 我试图用C#编写一个asp.net代码,该代码基本上将具有一个带有用户名和密码的登录页面。 If I enter username and pass as "admin" it will open the Admin.aspx . 如果输入用户名并以“ admin”身份通过,它将打开Admin.aspx

Likewise for "employee" it's employee.aspx and for "manager" it's manager.aspx . 同样,对于“雇员”,它是employee.aspx ,对于“经理”,它是manager.aspx

I have written quite a bit but stuck at the end.. please help how to open the appropriate page.. The username and password are stored in a database and I have to match it with the database 我已经写了很多,但最后还是停留了..请帮助如何打开适当的页面..用户名和密码存储在数据库中,我必须将其与数据库匹配

protected void Button1_Click(object sender, EventArgs e)
{
     SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=payroll;Integrated Security=True");
     SqlCommand cmd = new SqlCommand("Select employeeid FROM employees WHERE username='" + TextBox1.Text + "'and password='"+TextBox2.Text+"'", con);

     cmd.CommandType = CommandType.Text;
     cmd.Parameters.AddWithValue("@username", TextBox1.Text);
     cmd.Parameters.AddWithValue("@password", TextBox2.Text);

     con.Open();

     SqlDataReader dr = cmd.ExecuteReader();

     if (dr.Read())                         //I'M WRONG FROM HERE ONWARDS.
     {
        Response.Redirect("Admin.aspx"); 
     }

     con.Close();
     dr.Close();
}

You need one extra thing and that is dropdown list and that dropdown will be used to specify user type. 您还需要一件事,那就是dropdown list ,该下拉列表将用于指定用户类型。

Or better would be if you have separate page for each login type. 如果每种登录类型都有单独的页面,则更好。

if (dr.Read()){                         
  if(dr.HasRow()){
    if(dr["username"].ToLower() == "admin"){ 
        Response.Redirect("Admin.aspx");
    }else if (dr["username"].ToLower() == "manager") {
        Response.Redirect("manager.asp");
    }//and more else if   
  }                                                

}

You should: 你应该:

  • REALLY use parametrized query to avoid SQL injection and other messy business 真正使用参数化查询来避免SQL注入和其他混乱的业务
  • put all your disposable objects like SqlConnection and SqlCommand into using(...) { ... } blocks 将您所有的一次性对象(如SqlConnectionSqlCommand放入using(...) { ... }块中
  • read both the employeeid and the role of the employee to make the decision where to jump off to 阅读employeeid employeeidrole ,以决定跳转到哪里
  • avoid using AddWithValue which has its drawbacks (see ) 避免使用具有缺点的AddWithValue (请参阅AddWithValue
  • ALSO: you should NOT store your passwords in CLEAR TEXT in your table! 此外,您也应该不是你的密码储存在明文您的表! You should ALWAYS hash & salt your password - no exception 您应该始终对密码进行哈希处理和加盐-也不例外

Try this code: 试试这个代码:

protected void Button1_Click(object sender, EventArgs e)
{
    // define your connection string (typically from a .config file) and your query WITH parameters!
    string connectionString = "Data Source=(local);Initial Catalog=payroll;Integrated Security=True";
    string query = "SELECT employeeid, role FROM employees WHERE username=@user AND and password=@pwd;";

    // set up a connection and command in using() blocks
    using (SqlConnection con = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand(query, con))
    {
        // add parameters and set their values
        cmd.Parameters.Add("@user", SqlDbType.VarChar, 50).Value = TextBox1.Text;
        cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 50).Value = TextBox2.Text;

        // open connection
        con.Open();

        // establish data reader
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            // if at least one row is returned....  
            if (dr.Read()) 
            {  
                // get employee ID and role from the reader
                string employeeId = dr.GetFieldValue<string>(0);
                string role = dr.GetFieldValue<string>(1);

                // depending on role, jump off to various pages
                switch (role)
                {
                    case "admin":
                       Response.Redirect("Admin.aspx"); 
                       break;

                    case "manager":
                       Response.Redirect("manager.aspx"); 
                       break;

                    default:
                       Response.Redirect("employee.aspx"); 
                       break;
                    }
                } 
                else
                {
                   // what do you want to do if NO ROW was returned? E.g. user/pwd combo is wrong
                }

            dr.Close();
        }    

        con.Close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM