71 lines
1.8 KiB
Plaintext
71 lines
1.8 KiB
Plaintext
=== How to fix it in Spring
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
@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);
|
|
|
|
} catch (Exception e) {
|
|
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
|
|
}
|
|
|
|
return new ResponseEntity<>("Authentication Success", HttpStatus.OK);
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
@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[]
|
|
|