How To Prevent SQL Injections in Java

SQL Injection vulnerabilities have been on the OWASP Top 10 list since its beginning. They may appear in all languages including the Web’s two most popular languages: PHP and Java. SQL Injection vulnerabilities pose a serious threat to sensitive data and web application security in general. Attackers may use malicious code to get full control of the system.

To prevent SQL Injection attacks in Java, you must treat user input passed to the SQL queries as untrusted and avoid dynamic SQL queries created using simple string concatenation. If possible, you should validate input against a whitelist and use parametrized queries also known as prepared statements in Java JDBC. To show you how to do this, we will use a simple example where the web application displays information on fish.

Step 1: Validate input

If possible, validate the data supplied by the user against a whitelist. For example, in the example application, the fish species ID is an integer. After you obtain the fish species ID from the GET request, you can use the following to convert the parameter value to an integer:

int speciesId = Integer.parseInt(species);

Step 2: Prepare a query

Create your query using regular SQL commands. In the query, use question marks as placeholders to denote where you are using user-supplied data. For example:

String query = "SELECT name,description FROM fish_species WHERE species_id = ?";

Step 3: Create the prepared statement

Create the prepared SQL statement:

PreparedStatement stmt = connection.prepareStatement(query);

Note: Do not use connection.createStatement().

Step 4: Pass the parameters to the prepared statement

Bind your parameters to the query. For example, to bind the value of the fish species ID, use:

stmt.setInt(1,speciesId);

The 1 stands for first parameter. You can use setString, setFloat, or setDouble methods as well, depending on the parameter type.

Step 5: Execute your query

After you pass the parameters, you may execute your query. For example:

ResultSet results = stmt.executeQuery();

Step 6: Validate your application

To make sure that your application is secure, use Acunetix and run a website vulnerability scan for your website.

Conclusion

You can also create prepared statements in JPA using createQuery and setParameter methods. Prepared statements are the easiest method to protect your Java application against SQL Injection attacks but they are not the only one. Other methods include, for example, using stored procedures (supported by some databases). You may also use additional protection methods such as the least privilege rule (running database queries using users with very limited privileges).