定义防止sql注入的拦截器

/**
 * projectName micro-util
 * package com.open.util.handler.interceptor
 * className SqlInjectionInterceptor
 * <p>
 * description:
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2021/7/7 17:25
 */
@Slf4j
public class SqlInjectionInterceptor extends HandlerInterceptorAdapter {
    private static final String REGEX = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" + "(\\b(or|and|select|union|ascii|substr|into|chr|mid|char|declare|count|exec|insert|drop|grant|alter|delete|update|master|truncate|execute)\\b)";
    private static final Pattern PATTERN = Pattern.compile(REGEX, Pattern.CASE_INSENSITIVE);

    /**
     * This implementation always returns {@code true}.
     *
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        boolean hit = false;
        String targetString = null;
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String[] value = entry.getValue();
            for (String s : value) {
                if (!StringUtils.isEmpty(s) && PATTERN.matcher(s).find()) {
                    hit = true;
                    targetString = s;
                    break;
                }
            }
        }
        if (hit) {
            log.error("Sql injection hit [{}] in [{}]", targetString, request.getRequestURL());
            throw BAD_REQUEST.runtimeException("Param not support sql keys.");
        }
        return super.preHandle(request, response, handler);
    }
}
上一篇:shell变量的赋值方式


下一篇:logback配置文件