75 lines
1.9 KiB
Plaintext
75 lines
1.9 KiB
Plaintext
=== How to fix it in Java SE
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
@RestController
|
|
public class ApiController
|
|
{
|
|
@Autowired
|
|
Connection connection;
|
|
|
|
@GetMapping(value = "/authenticate")
|
|
@ResponseBody
|
|
public ResponseEntity<String> authenticate(
|
|
@RequestParam("user") String user,
|
|
@RequestParam("pass") String pass) throws SQLException
|
|
{
|
|
String query = "SELECT * FROM users WHERE user = '" + user + "' AND pass = '" + pass + "'";
|
|
|
|
try (Statement statement = connection.createStatement()) {
|
|
|
|
ResultSet resultSet = statement.executeQuery(query);
|
|
|
|
if (!resultSet.next()) {
|
|
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
|
|
Connection connection;
|
|
|
|
@GetMapping(value = "/authenticate")
|
|
@ResponseBody
|
|
public ResponseEntity<String> authenticate(
|
|
@RequestParam("user") String user,
|
|
@RequestParam("pass") String pass) throws SQLException
|
|
{
|
|
String query = "SELECT * FROM users WHERE user = ? AND pass = ?";
|
|
|
|
try (PreparedStatement statement = connection.prepareStatement(query)) {
|
|
statement.setString(1, user);
|
|
statement.setString(2, pass);
|
|
|
|
ResultSet resultSet = statement.executeQuery(query);
|
|
|
|
if (!resultSet.next()) {
|
|
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
|
|
}
|
|
}
|
|
|
|
return new ResponseEntity<>("Authentication Success", HttpStatus.OK);
|
|
}
|
|
}
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
include::../../common/fix/prepared-statements.adoc[]
|
|
|