SQLi – ASP.NET Secure Coding

Using Paramaterized Query/Prepared Statement

The use of parameterized stored procedures is an effective mechanism to avoid most forms of SQL Injection. Parameterized queries do proper substitution of arguments prior to running the SQL query. They completely remove the possibility of “dirty” input changing the meaning of your query.

// Build the query statement using parameterized query.

string sql = "SELECT UserId FROM Users WHERE " + "UserName = @UserName AND Password =@Password";
using (SqlCommand cmd = new SqlCommand(sql))
{   
    // Create the parameter objects as specific as possible.  
    cmd.Parameters.Add("@UserName", System.Data.SqlDbType.NVarChar, 50);   
    cmd.Parameters.Add("@Password", System.Data.SqlDbType.NVarChar, 25);
   
    // Add the parameter values.  Validation should have already happened. 
    cmd.Parameters["@UserName"].Value = UserName; 
    cmd.Parameters["@Password"].Value = Password;  
    cmd.Connection = connnection; 
    try
    {    
       cmd.Connection.Open();    
       var userId = cmd.ExecuteScalar();   
    }  
    catch (SqlException sx)   
    {    
       // Handle exceptions before moving on. 
    }
}

References
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
http://msdn.microsoft.com/en-us/library/ff648339.aspx

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *