Search code examples
c#sql-serversql-injection

SQL injection in C#


Is my code safe and secure ?

if (con.State == ConnectionState.Closed) 
    con.Open();

SqlCommand cmd4 = new SqlCommand();
cmd4.Connection = con;
cmd4.CommandText = "exec [Insert_Request] @FileCode = " + FileCodeArchiveID + ", @FirstName = '" + FirstName_RequestInsert_textBox.Text + "' ";
cmd4.ExecuteNonQuery();

if (con.State == ConnectionState.Open) 
     con.Close();

Or is it better to use cmd4.Parameters.Add() ?


Solution

  • As a general rule, avoid using string concatenation when building SQL commands/queries. Especially if one or more segments are coming from an untrusted source, like user input.

    You should do something like so:

         SqlCommand cmd4 = new SqlCommand();
         cmd4.Connection = con;
         cmd4.CommandType = CommandType.StoredProcedure;
         cmd4.CommandText = "Insert_Request";
         cmd4.Parameters.AddWithValue("@FileCode", FileCodeArchiveID);
         cmd4.Parameters.AddWithValue("@FirstName",FirstName_RequestInsert_textBox.Text); 
         cmd4.ExecuteNonQuery();
    

    For once, It's easier to read (in my opinion), and secondly using parameters sidesteps the sql injection vulnerability.