4. MyBatis - 深度学习 - 注入攻击

前言

在日常工作中我们需要时刻避免被注入攻击,否则可能你工作就没了

不安全的演示

使用 ${} 语法时,MyBatis 会直接注入原始字符串,即相当于拼接字符串,因而会导致 SQL 注入

<select id="selectStudentListLike" resultMap="StudentMap">
  SELECT * FROM student
  WHERE name = ${_parameter}
</select>
List<Student> selectStudentListLike(@Param("name") String name);

数据被全怼出来了

StudentMapper mapper = session.getMapper(StudentMapper.class);
List<Student> code = mapper.selectStudentListLike("'' or 1=1");
System.out.println(code);

避免SQl注入

使用 #{} 语法时,MyBatis 会自动生成 PreparedStatement

<select id="selectStudentListLike" resultMap="StudentMap">
  SELECT * FROM student
  WHERE name = #{name}
</select>

有时需要进行一些额外逻辑运行,通过 声明<bind>元素,并在其value 属性中添加运算脚本

<select id="selectStudentListLike" resultMap="StudentMap">
    <bind name="pattern" value="'%' + name + '%'"/>
    SELECT * FROM student 
    WHERE name LIKE #{pattern}
</select>

concat

<select id="selectStudentListLike" resultMap="StudentMap">
    SELECT * FROM student WHERE name LIKE concat ('%', #{name}, '%')
</select>

使用when + 默认值

<select id="selectUserListSortBy" resultMap="StudentMap">
  SELECT * FROM student 
 <choose>
    <when  test="sortBy == 'name' or sortBy == 'age'">
      order by ${sortBy}
    </when>
    <otherwise>
      order by name
    </otherwise>
 </choose>
</select>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章