60 lines
1.4 KiB
Plaintext
60 lines
1.4 KiB
Plaintext
![]() |
=== How to fix it in Dapper
|
||
|
|
||
|
include::../../common/fix/code-rationale.adoc[]
|
||
|
|
||
|
[cols="a"]
|
||
|
|===
|
||
|
h| Non-compliant code example
|
||
|
|
|
||
|
[source,csharp]
|
||
|
----
|
||
|
public class ExampleController : Controller
|
||
|
{
|
||
|
private readonly string ConnectionString;
|
||
|
|
||
|
public IActionResult Authenticate(string user, string pass)
|
||
|
{
|
||
|
using (var connection = new SqlConnection(ConnectionString))
|
||
|
{
|
||
|
var query = "SELECT * FROM users WHERE user = '" + use + "' AND pass = '" + pass + "'";
|
||
|
|
||
|
var result = connection.QueryFirst<User>(query); // Noncompliant
|
||
|
if (result == null) {
|
||
|
Unauthorized();
|
||
|
}
|
||
|
}
|
||
|
return Ok();
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
h| Compliant solution
|
||
|
|
|
||
|
[source,csharp]
|
||
|
----
|
||
|
public class ExampleController : Controller
|
||
|
{
|
||
|
private readonly string ConnectionString;
|
||
|
|
||
|
public IActionResult Authenticate(string user, string pass)
|
||
|
{
|
||
|
using (var connection = new SqlConnection(ConnectionString))
|
||
|
{
|
||
|
var query = "SELECT * FROM users WHERE user = @UserName AND password = @Password";
|
||
|
var parameters = new { UserName = user, Password = pass };
|
||
|
|
||
|
var result = connection.QueryFirst<User>(query, parameters);
|
||
|
if (result == null) {
|
||
|
Unauthorized();
|
||
|
}
|
||
|
}
|
||
|
return Ok();
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
|===
|
||
|
|
||
|
=== How does this work?
|
||
|
|
||
|
include::../../common/fix/prepared-statements.adoc[]
|
||
|
|