Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Sql Injection (Java)

I want to secure my application from SQL Injection attacks.

First question: What is better way to do it?

The first method: I convert every request to json here:

public JsonObject requestToJson(HttpServletRequest request) throws UnsupportedEncodingException{

        request.setCharacterEncoding("UTF-8");

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) { /*report an error*/ }

        return new JsonParser().parse(jb.toString()).getAsJsonObject();
    }

If it is best way, to prevent it here, then second question: how to do it here?

The second method: It can be done by Hibernate level. Second question: how to do it?

like image 519
annoirq Avatar asked Oct 19 '25 10:10

annoirq


1 Answers

Thanks this user: Elliott Frisch. He answered in comment.

JPARepository like this already prevented from SQL Injection:

public interface UserRepository extends JpaRepository<User, Integer> {
    User findByPhoneNumber(String phoneNumber);
}

Just need to prevent if you using HQL:

String query1 = "select * from MyBean where id = "+ id;
String query2 = "select * from MyBean where id = :id";

Second one, will be secured.

Thanks, everyone.

like image 199
annoirq Avatar answered Oct 21 '25 22:10

annoirq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!