Adam
Adam

Reputation: 161

SQL Injection using JPA Specification in REST Api

in my REST Controller I using Specification to build dynamic query, ie(its shorted version of this class, in real it had more fields):

public class FileHistorySpecification implements Specification<FileHistory> {


private String filename;

@Override
public Predicate toPredicate(Root<FileHistory> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
  final Collection<Predicate> predicates = new ArrayList<>();

    if(filename!=null) {
        final Predicate filenamePredicate = cb.like(root.get("filename"), "%"+filename+"%");
        predicates.add(filenamePredicate);
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}

}

It works fine, ie: when I typed: localhost:8080/fileshistory?filename=test it gives me all matching files files, but question is - is that safe? How to test if this is susceptible for sql injection?

Upvotes: 2

Views: 1640

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36173

Your code will create a query with bind variables. You can check this when setting the Hibernate logger org.hibernate.SQL to debug in application.properties

logging.level.org.hibernate.SQL=DEBUG

You should see a statement with ? placeholders.

Using bind variables prevents from SQL injection. Read more about this topic and how you could test it:

https://vladmihalcea.com/a-beginners-guide-to-sql-injection-and-how-you-should-prevent-it/

Upvotes: 4

Related Questions