1 SQL注入
入参参与SQL的编译,即会造成SQL注入,在入参中携带其他可执行的SQL语句,这些语句即时传入即时编译,会造成SQL注入。
如果SQL在入参以前即完成编译,出入的参数只作为参数的话,即可避免SQL注入。
MyBatis通过#{}接收的参数,避免了参数注入可执行语句,即在接收入参以前完成编译。
2 MyBatis
MyBatis有两种接收参数的方式,KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{},其中,``{}方式入参参与编译,无法避免SQL注入,#{}方式入参不参与编译,可避免SQL注入。
2.1 ${}实现SQL注入
- 入参
{
"username":"'admin' or 1=1",
"password":"admin",
"verifyCode":1
}
- SQL
<select id="login" parameterType="com.hardsoft.monkeyrun.modules.user.dto.UserInputDTO" resultType="com.hardsoft.monkeyrun.modules.user.dto.UserLoginOutputDTO">
SELECT
user_id userId,
username username,
password password
FROM
user_information
<where>
<if test="username !=null and username != ''">
and username = ${username}
</if>
and is_delete = #{deletedFlag}
</where>
</select>
2.1 #{}防止SQL注入
- 入参
{
"username":"admin",
"password":"admin",
"verifyCode":1
}
- SQL
<select id="login" parameterType="com.hardsoft.monkeyrun.modules.user.dto.UserInputDTO" resultType="com.hardsoft.monkeyrun.modules.user.dto.UserLoginOutputDTO">
SELECT
user_id userId,
username username,
password password
FROM
user_information
<where>
<if test="username !=null and username != ''">
and username = #{username}
</if>
and is_delete = #{deletedFlag}
</where>
</select>
【参考文献】
[1]https://blog.csdn.net/weixin_39986856/article/details/83651847