使用Hibernate防止SQL注入 [英] Prevent SQL injection with Hibernate

查看:198
本文介绍了使用Hibernate防止SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历Hibernate,我知道您可以使用HQL防止SQL注入:

I'm going through Hibernate and I know that you can prevent SQL injection with HQL:

String query1 = "from Obj where id = "+ id;
String query2 = "from Obj where id = :id";

query1是不安全的,而query2是安全的.

query1 is unsafe while query2 is safe.

如何使用Criteria实现安全查询?这已经实施吗?还是我需要做些其他事情?

How can I achieve safe queries with Criteria? Is this already implemented or do I have to do something else?

Criteria c = session.createCriteria(Obj.class);
c.add(Restrictions.eq("id", 5));

推荐答案

我正在经历Hibernate,我知道您可以使用HQL防止SQL注入:

I'm going through Hibernate and I know that you can prevent SQL injection with HQL:

这是一个非常普遍的误解,认为ORM解决方案(例如休眠)是SQL注入证明的. Hibernate允许使用本机SQL",并定义了一种专有的查询语言,称为HQL(休眠查询语言);前者易于进行SQL注入,而后者则易于进行HQL(或ORM)注入. 来源: http://software-security .sans.org/developer-how-to/fix-sql-injection-in-java-hibernate

It is a very common misconception that ORM solutions, like hibernate, are SQL Injection proof. Hibernate allows the use of "native SQL" and defines a proprietary query language, named, HQL (Hibernate Query Language); the former is prone to SQL Injection and the later is prone to HQL (or ORM) injection. Source: http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-hibernate

如何使用Criteria实现安全查询?

How can I achieve safe queries with Criteria? 

就后一个问题而言,标准API(类似于PreparedStatement)会转义参数,并且不会导致执行恶意SQL.

As far as you latter question is concerned, Criteria API (similar to PreparedStatement) escapes the parameters and won't cause malicious SQL to be executed.

只要您不将应用程序的参数直接连接到查询中(并使用Criteria,PreparedStatement),您的应用程序就是安全的.

As far as you don't concatenate your application's parameters directly into your query (and make use of Criteria, PreparedStatement), your app is safe.

这篇关于使用Hibernate防止SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆