简体   繁体   中英

is it safe using dynamic SQL with parameters? If not, what security issues might it be exposed to?

For example, this is the code that I am using:

String commandString = "UPDATE Members SET UserName = @newName , AdminLevel = @userLevel WHERE UserID = @userid";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString))
{
    SqlCommand cmd = new SqlCommand(commandString, conn);
    cmd.Parameters.Add("@newName", newName);
    cmd.Parameters.Add("@userLevel", userLevel);
    cmd.Parameters.Add("@userid", userid);
    conn.Open();
    cmd.ExecuteReader();
    Reader.Close();
}

That code looks fine. Parameterisation is the way to go, as opposed to concatenating user-supplied values in an adhoc SQL statement which can open you up to sql injection attacks. This can also help with execution plan reuse.

The only thing I'd add, is I prefer to explicitly define the datatype and sizes of the parameters. For example, if you don't then, as an example, all string values will get passed in to the database as NVARCHAR instead of VARCHAR. Hence I like to be explicit.

It's safe against SQL injection because it's parameterized. Other security concerns, such as ensuring that @userid is not spoofed, are separate security concerns that should be dealt with in other layers of your application.

That's still a static query string. It's not really "dynamic" sql until you also build parts of the string on the fly — something like this:

var sql = "SELECT columns FROM Table WHERE 1=1";
if (!string.IsNullOrEmpty(txtName.Text)) sql += " AND Name LIKE '%' + @Name + '%'";
if (!string.IsNullOrEmpty(txtDesc.Text)) sql += " AND CONTAINS(DESCRIPTION, @description)";

But even so, this is still "safe" in the sql injection sense as long as you continue to use parameters for every part of the query that originates with user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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