Login for C# 中的存储过程和参数

我一直在做一个项目,我对 C# 很陌生。我有正确的登录,但它容易受到 SQL 注入攻击。这是我的代码 - 任何人都可以帮助我如何应用带有参数的存储过程,以便它可以更安全吗?


protected void Button1_Click(object sender, EventArgs e)

{

    string Cs = ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString;


    using(SqlConnection con=new SqlConnection(Cs))

    {

        SqlCommand cmd = new SqlCommand("Select * from Users where Username= '" + Username.Text + "' And " +

                    "Password='" + Password.Text+ "'", con);


        con.Open();


        SqlDataAdapter sda = new SqlDataAdapter(cmd);


        DataTable dt = new DataTable();

        sda.Fill(dt);


        if (dt.Rows.Count != 0)

        {

            Response.Redirect("~/Cuhome.aspx");

        }

        else

        {

            LblError.Text = "Invalid Username & Password";

        }

    }

}

谢谢


慕莱坞森
浏览 168回答 1
1回答

沧海一幻觉

您不一定需要存储过程 - 只需使用正确参数化的查询 - 即可实现“更安全”的相同目标:protected void Button1_Click(object sender, EventArgs e){    string Cs = ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString;    // set up query - using PARAMETERS as you always should!    // Also: you don't seem to need the *whole* row - all the columns of "Users" - so select just what you **really need**!    string query = "Select UserId from Users where username = @username and password = @password;";    // put both SqlConnection *AND* SqlCommand into "using" blocks    using (SqlConnection con=new SqlConnection(Cs))    using (SqlCommand cmd = new SqlCommand(query, con))    {        // provide the parameters        cmd.Parameters.Add("@username", SqlDbType.VarChar, 100).Value = Username.Text;        cmd.Parameters.Add("@password", SqlDbType.VarChar, 100).Value = Password.Text;        // use an ExecuteScalar call to get the UserId from Users - and check if it exists        con.Open();        object result = cmd.ExecuteScalar();        // if we get something back --> the user with this password exists --> redirect        if (result != null)        {            Response.Redirect("~/Cuhome.aspx");        }        else        {            LblError.Text = "Invalid Username & Password";        }    }}但是这段代码还有一个更可怕的缺陷:您似乎将用户的密码存储在数据库表中的 PLAIN TEXT中!这是任何安全站点的主要禁忌-永远不要以纯文本形式存储密码!如果您实际存储它们,则需要散列和加盐密码。
打开App,查看更多内容
随时随地看视频慕课网APP