简体   繁体   English

防止SQL注入 - mybatis和spring

[英]Prevent against SQL Injection - mybatis and spring

Is there exists a good way to prevent agains SQL injection in mybatis ? 是否存在以防止agains SQL注入的好办法mybatis
I am using this in connection to spring-boot . 我正在使用它与spring-boot In reality, I am using string param given by user in queries. 实际上,我在查询中使用用户给出的字符串参数。
Any ideas? 有任何想法吗?

In general, you should consider using #{} for string substitution instead of ${} . 通常,您应该考虑使用#{}进行字符串替换而不是${}

This is because #{} causes Mybatis to create a preparedStatement which prevents SQLInjection compared to ${} which would inject unmodified string into SQL. 这是因为#{}导致Mybatis创建一个preparedStatement ,它会阻止SQLInjection与${}相比,这会将未修改的字符串注入SQL。

Mybatis clearly explains the same in its documentation here . MyBatis的清楚地解释它的文档在同一个位置 (String Substitution Section) (字符串替换部分)

You can also refer to this blog which provides examples on String substitution with mybatis and how SQLInjection can be stopped. 您还可以参考此博客 ,其中提供了有关使用mybatis进行字符串替换以及如何停止SQLInjection的示例。

@Bandi Kishore is absolutely right, to complement his response I think it's worth explaining the reason why prepared statements prevents SQLInjection by nature, as greatly explained in this article @Bandi Kishore是绝对正确的,为了补充他的回答,我认为值得解释为什么预备语句本质上阻止SQLInjection的原因,正如本文中大大解释的那样

Basically the SQL server engine will compile your query string and then substitute its parameters. 基本上SQL服务器引擎将编译您的查询字符串,然后替换其参数。

Query using string substitution: If you pass a query string already with the parameters substituted then the compiled query code will include the malicious code compiled as valid SQL commands. 使用字符串替换进行查询如果已传递已替换参数的查询字符串,则编译的查询代码将包含编译为有效SQL命令的恶意代码。

Query using placeholders: On the other hand if the query string only has the placeholders the SQL server engine will compile the code first with the placeholders, then it will substitute the place holder with the values provided (at this point the malicious code is inserted), however, since the malicious code was not compiled it'll be treated as pure data by the SQL server engine thus having prevented the malicious attack. 使用占位符查询:另一方面,如果查询字符串只有占位符,SQL服务器引擎将首先使用占位符编译代码,那么它将使用提供的值替换占位符(此时插入恶意代码)但是,由于恶意代码未编译,因此SQL Server引擎将其视为纯数据,从而防止了恶意攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM