Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent SQL Injection with JPA and Hibernate?

I am developing an application using hibernate. When I try to create a Login page, The problem of Sql Injection arises. I have the following code:

@Component @Transactional(propagation = Propagation.SUPPORTS) public class LoginInfoDAOImpl implements LoginInfoDAO{  @Autowired private SessionFactory sessionFactory;       @Override public LoginInfo getLoginInfo(String userName,String password){     List<LoginInfo> loginList = sessionFactory.getCurrentSession().createQuery("from LoginInfo where userName='"+userName+"' and password='"+password+"'").list();     if(loginList!=null )         return loginList.get(0);     else return null;              }       } 

How will i prevent Sql Injection in this scenario ?The create table syntax of loginInfo table is as follows:

create table login_info   (user_name varchar(16) not null primary key,   pass_word varchar(16) not null);  
like image 838
Mr. Singthoi Avatar asked Dec 31 '12 13:12

Mr. Singthoi


People also ask

Does hibernate protect against SQL injection?

Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please. There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.

Does JPA repository prevent SQL injection?

This is a common misconception. JPA and other ORMs relieves us from creating hand-coded SQL statements, but they won't prevent us from writing vulnerable code.

How hibernate prevent SQL injection in Java?

We should always try to use stored Procedures in general to prevent SQLInjection.. If stored procedures are not possible; we should try for Prepared Statements. I agree, it is technically better, because of speed. however, no ORM framework I know of in any language generates stored procedure s.


1 Answers

Query q = sessionFactory.getCurrentSession().createQuery("from LoginInfo where userName = :name"); q.setParameter("name", userName); List<LoginInfo> loginList = q.list(); 

You have other options too, see this nice article from mkyong.

like image 116
Petr Mensik Avatar answered Sep 20 '22 09:09

Petr Mensik