【问题标题】:How to validate password and redirect admin to admin page and user to user page using roles? [closed]如何使用角色验证密码并将管理员重定向到管理页面和用户到用户页面? [关闭]
【发布时间】:2014-05-01 13:44:01
【问题描述】:

这是我的代码:

protected void loginBtn_Click(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["userDatabaseConnectionString1"].ConnectionString);
        conn.Open();
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand("select role from accounts", conn);
        SqlDataAdapter da = new SqlDataAdapter();

        cmd.CommandType = CommandType.Text;
        da.SelectCommand = cmd;
        da.Fill(ds);

        if (ds.Tables[0].Rows.Count > 0)
        {
            string role = Convert.ToString(ds.Tables[0].Rows[0]["role"]);


            if (role == "a")
            {
                Response.Redirect("AdminPage/adminAccount.aspx");
             }
            if (role == "u")
            {
                Response.Redirect("UserPage/userAccount.aspx");
            }
        }
        else
        {

            //record is not in ur table
        }

    }
}

角色a 用于管理员,角色u 用于用户。

如何验证和重定向正确登录的用户?

现在,无论用户名和密码是否正确,只要我单击登录,此代码都会将我重定向到管理主页。

我需要添加什么来解决这个问题?

【问题讨论】:

    标签: c# html visual-studio


    【解决方案1】:
    SqlCommand cmd = new SqlCommand("select role from accounts where Username=@Username and Password=@Password", conn);
    cmd.Parameters.AddWithValue("@Username",txtUsername.Text);
    cmd.Parameters.AddWithValue("@Password",txtPassword.Text);
    

    【讨论】:

    • 使用参数的答案比其他 2 好得多!! +1
    【解决方案2】:

    你不知道自己在做什么

    请在我试图解释你的时候提出一些逻辑

      SqlCommand cmd = new SqlCommand("select role from accounts", conn);
    

    这行会返回所有用户对吗?

    但是你需要特定的用户数据所以这样写

     SqlCommand cmd = new SqlCommand("select role from accounts where username='"+yourusernametextbox.text+"' and password='"+yourpassword.text+"'--", conn);
    

    这将返回角色为管理员或用户的真实结果

    现在给你一个建议

    这样的格式化查询可能会导致 sql 注入,请使用参数化查询

    【讨论】:

    • 非常感谢您的成功!我非常迷茫,谢谢!!!
    【解决方案3】:

    您的密码和用户名字符串在哪里?您如何检查用户输入的内容是否有效?获得后,您可以通过以下方式使用它们:

    SqlCommand cmd = new SqlCommand("select role from accounts where username = '" + usernameString + "' and password = '" + passwordString + "'", conn);
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多