我已经使用hibernate与我的数据库进行交互,现在我想让我的数据库层对SQL注入(inject)安全,所以我做了一些研究,我发现我的查询应该是参数化的,这是否意味着我只是构建我的HQL查询作为:
List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();
然后它被参数化并受到 SQL 注入(inject)的保护,或者还有其他我需要做的事情......
还提到了另一件事-“ 始终逃避您的数据”如何实现?
最佳答案
我不知道 setString()
但如果它与 setParameter()
相同那么是的,这样做足以防止sql注入(inject)。
更新
通过转义数据,意味着您必须确保您没有在数据库中存储危险值。
例如,如果您传入参数
String name = "<script>alert('Hello');</script>";
//insert this name into Mother, and then when you load it from the database, it will be displayed
List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();
到您的查询,然后下次从数据库中加载它并在您的网络浏览器中呈现它时,它将运行脚本。
您需要确保您的框架转义所有非法字符,即:更改
<
至<
在将其插入数据库之前。如果您的框架不这样做,则必须手动进行。
有大量的库可以为您正确转义代码。看看this question例如和那里的答案。
关于hibernate - 在 Hibernate 中防止 SQL 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4606505/