简体   繁体   中英

Prevent against SQL Injection - mybatis and spring

Is there exists a good way to prevent agains SQL injection in mybatis ?
I am using this in connection to 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 clearly explains the same in its documentation here . (String Substitution Section)

You can also refer to this blog which provides examples on String substitution with mybatis and how SQLInjection can be stopped.

@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

Basically the SQL server engine will compile your query string and then substitute its parameters.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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