Bootstrap

java解决sql注入完整的工具类

java解决sql注入完整的工具类

工具类

package kl.gw.adc.cms.util;

import kl.gw.cloud.common.exception.ApiException;
import kl.gw.cloud.common.model.Condition;
import org.apache.commons.lang.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author sunrj
 */
public class RegexUtils {

    /**
     * 对Condition校验防止sql注入
     *
     * @param condition
     */
    public static void verifyCondition(Condition condition) {

        //filter校验
        Optional.ofNullable(condition.getFilter()).ifPresent(map -> map.forEach((key, value) -> {
            if (!key.contains("\"name\"")) {
                //校验key
                boolean rightfulKey = RegexUtils.isRightfulString(key);
                if (!rightfulKey) {
                    throw new ApiException(400, "filter参数中含有非法的列名:" + key);
                }
                //校验value
                for (String s : value) {
                    if (s.contains("'")) {
                        throw new ApiException(400, "filter参数中的值非法:" + value);
                    }
                }
            }
        }));

        //gte校验
        Optional.ofNullable(condition.getGte()).ifPresent(map -> map.forEach((key, value) -> {
            boolean rightfulkey = RegexUtils.isRightfulString(key);
            //校验key
            if (!rightfulkey) {
                throw new ApiException(400, "gte参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //lte校验
        Optional.ofNullable(condition.getLte()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "lte参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //gt校验
        Optional.ofNullable(condition.getGt()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "gt参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //lt校验
        Optional.ofNullable(condition.getLt()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "lt参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //page校验
        Optional.ofNullable(condition.getPage()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "page参数中含有非法的列名:" + key);
            }
            //校验value
            boolean rightfulValue = RegexUtils.isRightfulString(String.valueOf(value));
            if (!rightfulValue) {
                throw new ApiException(400, "page参数中含有非法的值:" + value);
            }
        }));

        //sort校验
        Optional.ofNullable(condition.getSort()).ifPresent(map -> map.forEach((s) -> {
            boolean rightfulString = RegexUtils.isRightfulString(s);
            if (!rightfulString) {
                throw new ApiException(400, "sort参数中含有非法的列名:" + s);
            }
        }));

        //group校验
        Optional.ofNullable(condition.getGroup()).ifPresent(list -> list.forEach((s) -> {
            if (!s.contains("time(") && !s.contains("\"name\"")) {
                boolean rightfulString = RegexUtils.isRightfulString(s);
                if (!rightfulString) {
                    throw new ApiException(400, "group参数中含有非法的列名:" + s);
                }
            }
        }));
    }

    private static void verifyTime(String key, String value) {
        if ("time".equals(key)){
            boolean rightfulValue = RegexUtils.validDateStr(value, "");
            boolean rightfulValue2 = RegexUtils.validDateStr(value, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            //value不为yyyy-MM-dd'T'HH:mm:ss.SSS'Z'格式也不为yyyy-MM-dd HH:mm:ss时间格式时
            if (!rightfulValue && !rightfulValue2) {
                throw new ApiException(400, "参数的时间格式非法:" + value);
            }
        }else {
            boolean rightfulValue = RegexUtils.isRightfulString(value);
            if (!rightfulValue) {
                throw new ApiException(400, "参数中含有非法的列名:" + value);
            }
        }
    }

    /**
     * 判断是否为合法字符(a-zA-Z0-9-_)
     *
     * @param text
     * @return
     */
    public static boolean isRightfulString(String text) {
        return match(text, "^[A-Za-z0-9_-]+$");
    }

    /**
     * 正则表达式匹配
     *
     * @param text 待匹配的文本
     * @param reg  正则表达式
     * @return
     */
    private static boolean match(String text, String reg) {
        if (StringUtils.isBlank(text) || StringUtils.isBlank(reg)) {
            return false;
        }
        return Pattern.compile(reg).matcher(text).matches();
    }

    /**
     * 校验时间字符串是否合法
     *
     * @param dateStr the date str
     * @param pattern the pattern
     * @return the boolean
     */
    public static boolean validDateStr(String dateStr, String pattern) {
        if (StringUtils.isEmpty(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            LocalDate.parse(dateStr, new DateTimeFormatterBuilder().appendPattern(pattern).parseStrict().toFormatter());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}


在需要校验的地方引用即可

@GetMapping
 @ApiOperation(value = "查询用户列表", notes = "查询用户列表")
 public ServerResponse<IPage<AccountManageVo>> queryAccount(Page<AccountManageVo> page) {
     //校验page中的字段,防止sql注入
  RegexUtils.verifyPageFileld(page);
  return ServerResponse.successMethod(accountManageService.queryAccount(page));
 }
;