73 lines
1.8 KiB
Plaintext
73 lines
1.8 KiB
Plaintext
![]() |
=== How to fix it in Spring
|
||
|
|
||
|
include::../../common/fix/code-rationale.adoc[]
|
||
|
|
||
|
[cols="a"]
|
||
|
|===
|
||
|
h| Non-compliant code example
|
||
|
|
|
||
|
[source,java]
|
||
|
----
|
||
|
@RestController
|
||
|
public class ApiController
|
||
|
{
|
||
|
@Autowired
|
||
|
JdbcTemplate jdbcTemplate;
|
||
|
|
||
|
@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 {
|
||
|
BeanPropertyRowMapper<User> userType = new BeanPropertyRowMapper(User.class);
|
||
|
User queryResult = jdbcTemplate.queryForObject(query, userType); // Noncompliant
|
||
|
|
||
|
} 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
|
||
|
JdbcTemplate jdbcTemplate;
|
||
|
|
||
|
@GetMapping(value = "/authenticate")
|
||
|
@ResponseBody
|
||
|
public ResponseEntity<String> authenticate(
|
||
|
@RequestParam("user") String user,
|
||
|
@RequestParam("pass") String pass)
|
||
|
{
|
||
|
String query = "SELECT * FROM users WHERE user = ? AND pass = ?";
|
||
|
|
||
|
try {
|
||
|
BeanPropertyRowMapper<User> userType = new BeanPropertyRowMapper(User.class);
|
||
|
User queryResult = jdbcTemplate.queryForObject(query, userType, user, pass);
|
||
|
|
||
|
} 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[]
|
||
|
|