Intercept GET requests in Springboot to obtain request parameters to verify legality

Table of contents

Purpose

core method

full code

        create interceptor

        register interceptor

Test effect


Purpose

        Create an interceptor in Springboot to intercept all GET type requests, obtain request parameters to verify the legality of the content and prevent SQL injection (this method is only suitable for intercepting GET type requests, POST type request parameters are in the body, so the following method is not applicable).

core method

        1. Intercept http://127.0.0.1:8088/api/checkTechCertInfoCancel?name=ljh type:

Map<String, String[]> parameterMap = request.getParameterMap();

        2. Intercept  http://127.0.0.1:8088/api/checkTechCertInfoCancel/ljh type:

Map<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

full code

        create interceptor

import com.alibaba.fastjson.JSON;
import com.boc.ljh.utils.Result;
import com.boc.ljh.utils.status.AppErrorCode;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * @Author: ljh
 * @ClassName SqlInterceptor
 * @Description 拦截器 用于拦截GET请求校验参数内容
 * @date 2023/8/9 10:12
 * @Version 1.0
 */
@Component
public class SqlInterceptor implements HandlerInterceptor {

    /**
     * @Author: ljh
     * @Description: 在controller前拦截请求
     * @DateTime: 10:38 2023/8/9
     * @Params:
     * @Return
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        System.err.println(request.getMethod());
        if (request.getMethod().equals("GET") && request.getRequestURI().contains("?")) {
            //获取EGT请求中的参数,例如http://127.0.0.1:8088/api/checkTechCertInfoCancel?name=ljh 请求中的参数ljh
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String[] value = entry.getValue();
                for (String s : value) {
                    //校验参数值是否合法
                    if (verifySql(s)) {
                        response.setContentType("application/json;charset=utf-8");
                        Result result = new Result();
                        result.setMessage("请求参数中含有非法字符!请检查重新输入");
                        result.setStatus(500);
                        response.getWriter().write(JSON.toJSONString(result));
                        return false;
                    }
                }
            }
        } else {
            //获取EGT请求中的参数,例如http://127.0.0.1:8088/api/checkTechCertInfoCancel/ljh 请求中的参数ljh
            Map<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            for (String key : pathVariables.keySet()) {
                //校验参数值是否合法
                if (verifySql(pathVariables.get(key))) {
                    //返回错误提示
                    response.setContentType("application/json;charset=utf-8");
                    Result result = new Result();
                    result.setMessage("请求参数中含有非法字符!请检查重新输入");
                    result.setStatus(500);
                    response.getWriter().write(JSON.toJSONString(result));
                    return false;
                }
            }
        }
        return true;
    }

    //处理请求完成后视图渲染之前的处理操作
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    //视图渲染之后的操作
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }


    /**
     * @Author: ljh
     * @Description: 校验非法字符
     * @DateTime: 11:15 2023/8/9
     * @Params:
     * @Return
     */
    public boolean verifySql(String parameter) {
        String s = parameter.toLowerCase();
        // 过滤掉的sql关键字,特殊字符前面需要加\\进行转义
        String badStr =
                "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|" +
                        "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
                        "information_schema.columns|table_schema|union|where|order|by|" +
                        "'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";

        //使用正则表达式进行匹配
        boolean matches = s.matches(badStr);
        return matches;
    }

        register interceptor

/**
 * @Author: ljh
 * @ClassName MvcInterceptorConfig
 * @Description 注册SqlInterceptor拦截器到容器中
 * @date 2023/8/9 10:21
 * @Version 1.0
 */

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcInterceptorConfig implements WebMvcConfigurer {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SqlInterceptor()) //需要注册到容器中的拦截器
                .addPathPatterns("/**"); //所有请求都被拦截,静态资源也被拦截
//                .excludePathPatterns("/", "/login", "/css/**", "/fonts/**", "/images/**", "/js/**"); // 放行的请求
    }

}

Test effect

       The content of the request is legal:

        Request content is illegal:

Springboot uses filters to verify PSOT type request parameter contenticon-default.png?t=N6B9 https://blog.csdn.net/weixin_45151960/article/details/132187495?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/weixin_45151960/article/details/132184917