外卖霸王餐API防SQL注入进阶:Java MyBatis中#{}与${}的正确使用边界及自定义TypeHandler拦截恶意参数

📅 2026/7/20 20:34:11 👁️ 阅读次数 📝 编程学习
外卖霸王餐API防SQL注入进阶:Java MyBatis中#{}与${}的正确使用边界及自定义TypeHandler拦截恶意参数

外卖霸王餐API防SQL注入进阶:Java MyBatis中#{}与${}的正确使用边界及自定义TypeHandler拦截恶意参数

背景:霸王餐业务中的SQL注入风险

作为外卖霸王餐API唯一供给源头,同时也是霸王餐外卖CPS取链源头,俱美开放平台深知API安全的重要性。在海量订单、用户、商户数据的交互中,SQL注入是最高危的漏洞之一。攻击者可通过恶意参数窃取数据、篡改订单甚至删除核心业务记录。

虽然MyBatis提供了#{}${}两种参数绑定方式,但许多开发者对其安全边界理解不清,导致注入风险潜伏在代码中。本文将深入剖析两者的本质区别,并通过自定义TypeHandler实现主动防御机制。

#{}与${}的本质区别

#{}是预编译参数占位符,MyBatis会将其转换为?,并通过PreparedStatement.setXXX()方法安全赋值,从根本上防止SQL注入。

// 安全:使用#{},参数被当作值处理@Select("SELECT * FROM t_order WHERE order_id = #{orderId}")OrderselectOrder(StringorderId);

${}是字符串替换,MyBatis直接将参数值拼接到SQL中,极易引发注入。

// 危险:使用${},参数被直接拼接@Select("SELECT * FROM t_order WHERE order_id = '${orderId}'")OrderselectOrder(StringorderId);

orderId传入1' OR '1'='1,SQL变为:

SELECT*FROMt_orderWHEREorder_id='1'OR'1'='1'

导致全表数据泄露。

正确使用边界:何时能用${}

${}仅适用于SQL结构动态化场景,如表名、排序字段、动态列名,且必须严格白名单校验。

packagebaodanbao.com.cn.mapper;importorg.apache.ibatis.annotations.Select;importorg.apache.ibatis.annotations.Param;importjava.util.List;importjava.util.Map;/** * 订单Mapper * @author baodanbao.com.cn */publicinterfaceOrderMapper{/** * 动态排序查询(仅限白名单字段) */@Select("<script>"+"SELECT order_id, user_id, amount FROM t_order "+"WHERE status = #{status} "+"<if test='sortBy != null'>ORDER BY ${sortBy}</if>"+"</script>")List<Map<String,Object>>selectOrders(@Param("status")Stringstatus,@Param("sortBy")StringsortBy);}

但必须在Service层校验sortBy

packagebaodanbao.com.cn.service;importbaodanbao.com.cn.mapper.OrderMapper;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.Arrays;importjava.util.List;importjava.util.Map;/** * 订单服务 * @author baodanbao.com.cn */@ServicepublicclassOrderService{privatestaticfinalList<String>ALLOWED_SORT_FIELDS=Arrays.asList("order_id","amount","create_time");@AutowiredprivateOrderMapperorderMapper;publicList<Map<String,Object>>getOrders(Stringstatus,StringsortBy){// 白名单校验if(sortBy!=null&&!ALLOWED_SORT_FIELDS.contains(sortBy)){thrownewIllegalArgumentException("非法排序字段");}returnorderMapper.selectOrders(status,sortBy);}}

进阶防御:自定义TypeHandler拦截恶意参数

即使使用#{},若参数本身包含恶意SQL片段(如用于LIKE查询),仍可能被利用。我们通过自定义TypeHandler实现主动检测。

packagebaodanbao.com.cn.security.typehandler;importorg.apache.ibatis.type.BaseTypeHandler;importorg.apache.ibatis.type.JdbcType;importorg.apache.ibatis.type.MappedJdbcTypes;importorg.apache.ibatis.type.MappedTypes;importjava.sql.*;importjava.util.regex.Pattern;/** * 防SQL注入字符串TypeHandler * 拦截常见SQL注入关键字 * @author baodanbao.com.cn */@MappedJdbcTypes(JdbcType.VARCHAR)@MappedTypes(String.class)publicclassSafeStringTypeHandlerextendsBaseTypeHandler<String>{// 常见SQL注入关键字正则privatestaticfinalPatternSQL_INJECTION_PATTERN=Pattern.compile("(?i)\\b(union|select|insert|update|delete|drop|alter|exec|execute|waitfor|sleep|benchmark)\\b");@OverridepublicvoidsetNonNullParameter(PreparedStatementps,inti,Stringparameter,JdbcTypejdbcType)throwsSQLException{// 检测恶意内容if(SQL_INJECTION_PATTERN.matcher(parameter).find()){thrownewSQLException("检测到SQL注入风险参数: "+parameter);}ps.setString(i,parameter);}@OverridepublicStringgetNullableResult(ResultSetrs,StringcolumnName)throwsSQLException{returnrs.getString(columnName);}@OverridepublicStringgetNullableResult(ResultSetrs,intcolumnIndex)throwsSQLException{returnrs.getString(columnIndex);}@OverridepublicStringgetNullableResult(CallableStatementcs,intcolumnIndex)throwsSQLException{returncs.getString(columnIndex);}}
注册TypeHandler

在MyBatis配置中注册:

packagebaodanbao.com.cn.config;importorg.apache.ibatis.session.SqlSessionFactory;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importjavax.sql.DataSource;/** * MyBatis配置 * @author baodanbao.com.cn */@ConfigurationpublicclassMyBatisConfig{@BeanpublicSqlSessionFactorysqlSessionFactory(DataSourcedataSource)throwsException{SqlSessionFactoryBeanfactoryBean=newSqlSessionFactoryBean();factoryBean.setDataSource(dataSource);factoryBean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));// 注册自定义TypeHandlerorg.apache.ibatis.session.Configurationconfiguration=neworg.apache.ibatis.session.Configuration();configuration.getTypeHandlerRegistry().register(String.class,baodanbao.com.cn.security.typehandler.SafeStringTypeHandler.class);factoryBean.setConfiguration(configuration);returnfactoryBean.getObject();}}
实体类中使用
packagebaodanbao.com.cn.entity;importbaodanbao.com.cn.security.typehandler.SafeStringTypeHandler;importorg.apache.ibatis.type.Alias;/** * 用户实体 * @author baodanbao.com.cn */@Alias("User")publicclassUser{privateLongid;// 自动使用SafeStringTypeHandlerprivateStringusername;privateStringphone;// getter/setterpublicLonggetId(){returnid;}publicvoidsetId(Longid){this.id=id;}publicStringgetUsername(){returnusername;}publicvoidsetUsername(Stringusername){this.username=username;}publicStringgetPhone(){returnphone;}publicvoidsetPhone(Stringphone){this.phone=phone;}}

通过#{}为主 + ${}白名单 + TypeHandler主动拦截三重防护,俱美开放平台构建了外卖霸王餐API的SQL注入防御体系,作为霸王餐外卖CPS取链源头,我们持续守护每一笔交易的安全。

本文著作权归 俱美开放平台 ,转载请注明出处!