为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕莱坞森 2021-11-14 17:20:04
我一直在做一个项目,我对 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";        }    }}谢谢
查看完整描述

1 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

您不一定需要存储过程 - 只需使用正确参数化的查询 - 即可实现“更安全”的相同目标:


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中!这是任何安全站点的主要禁忌-永远不要以纯文本形式存储密码!如果您实际存储它们,则需要散列和加盐密码。


查看完整回答
反对 回复 2021-11-14
  • 1 回答
  • 0 关注
  • 165 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信