4

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?

7
  • How would converting the request to JSON prevent SQL Injection? Why do you think HIbernate is vulnerable to SQL Injection? Commented Nov 18, 2015 at 5:23
  • no, converting to json is not preventing injection of course. I mean, as I'm converting every request to json, I can put this validation in this function. Commented Nov 18, 2015 at 5:25
  • I'm new in hibernate. I'm using several ways to generate SQL: JPARepository, CriteriaBuilder and HQL. My question is: "it's already preventing from SQL Injection"? Commented Nov 18, 2015 at 5:27
  • See this question and this question. Commented Nov 18, 2015 at 5:32
  • Ok, about HQL, JpaRepository I understood. But what about CriteriaBuilder. Is it safe? Commented Nov 18, 2015 at 5:35

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.