Search code examples
javaspringhibernatesql-injection

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?


Solution

  • 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.