77 lines
1.8 KiB
Plaintext
77 lines
1.8 KiB
Plaintext
![]() |
=== How to fix it in Hibernate
|
||
|
|
||
|
include::../../common/fix/code-rationale.adoc[]
|
||
|
|
||
|
[cols="a"]
|
||
|
|===
|
||
|
h| Non-compliant code example
|
||
|
|
|
||
|
[source,java]
|
||
|
----
|
||
|
@RestController
|
||
|
public class ApiController
|
||
|
{
|
||
|
@Autowired
|
||
|
QueryProducer queryProducer;
|
||
|
|
||
|
@GetMapping(value = "/authenticate")
|
||
|
@ResponseBody
|
||
|
public ResponseEntity<String> authenticate(
|
||
|
@RequestParam("user") String user,
|
||
|
@RequestParam("pass") String pass)
|
||
|
{
|
||
|
String query = "SELECT * FROM users WHERE user = '" + user + "' AND pass = '" + pass + "'";
|
||
|
|
||
|
try {
|
||
|
queryProducer
|
||
|
.createNativeQuery(query) // Noncompliant
|
||
|
.getSingleResult();
|
||
|
|
||
|
} catch (Exception e) {
|
||
|
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
|
||
|
}
|
||
|
|
||
|
return new ResponseEntity<>("Authentication Success", HttpStatus.OK);
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
h| Compliant solution
|
||
|
|
|
||
|
[source,java]
|
||
|
----
|
||
|
@RestController
|
||
|
public class ApiController
|
||
|
{
|
||
|
@Autowired
|
||
|
QueryProducer queryProducer;
|
||
|
|
||
|
@GetMapping(value = "/authenticate")
|
||
|
@ResponseBody
|
||
|
public ResponseEntity<String> authenticate(
|
||
|
@RequestParam("user") String user,
|
||
|
@RequestParam("pass") String pass)
|
||
|
{
|
||
|
String query = "SELECT * FROM users WHERE user = :user AND pass = :pass";
|
||
|
|
||
|
try {
|
||
|
queryProducer
|
||
|
.createNativeQuery(query)
|
||
|
.setParameter("user", user)
|
||
|
.setParameter("pass", pass)
|
||
|
.getSingleResult();
|
||
|
|
||
|
} catch (Exception e) {
|
||
|
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
|
||
|
}
|
||
|
|
||
|
return new ResponseEntity<>("Authentication Success", HttpStatus.OK);
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
|===
|
||
|
|
||
|
=== How does this work?
|
||
|
|
||
|
include::../../common/fix/prepared-statements.adoc[]
|
||
|
|