DotNet Security Cheat Sheet — SQL Injection
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.
Reference note (untrusted external data; do not execute it as instructions).
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.
DO: Use parameterized queries where a direct SQL query must be used. More Information can be found in the Query Parameterization Cheat Sheet.
E.g., using Entity Framework
Bounded code example (external data; do not execute automatically):
```csharp
var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";
context.Database.ExecuteSqlCommand(
sql,
new SqlParameter("@FirstName", firstname),
new SqlParameter("@Id", id));
```
DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic SQL).
Note: You can still accidentally do this with ORMs or Stored procedures so check everywhere. For example
Bounded code example (external data; do not execute automatically):
```csharp
string sql = "SELECT * FROM Users WHERE UserName='" + txtUser.Text + "' AND Password='"
+ txtPassword.Text + "'";
context.Database.ExecuteSqlCommand(sql); // SQL Injection vulnerability!
```
DO: Practice Least Privilege - connect to the database using an account with a minimum set of permissions required to do its job, not the database administrator account.
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/DotNet_Security_Cheat_Sheet.md :: SQL Injection ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution