如何为Springboot项目增加一个xss过滤器呢?

书欣 SpringBoot 发布时间:2023-01-04 09:15:50 阅读数:13950 1
下文笔者讲述SpringBoot项目中,为了避免xss攻击,添加xss过滤器的方法分享,如下所示
实现思路:
    1.定义xss开启配置
	2.编写相应的过滤器,并将过滤器添加到springBoot项目的过滤器链上
例:
application.xml文件添加配置

# 防止XSS攻击
xss:
  # 过滤开关
  enabled: true
  # 排除链接(多个用逗号分隔)
  excludes: /system/notice
  # 匹配链接
  urlPatterns: /sale/list
    #/system/*,/monitor/*,/tool/*,/sale/list
  
//过滤器配置类
@Configuration
public class FilterConfig {

    @Value("${xss.excludes}")
    private String excludes;

    @Value("${xss.urlPatterns}")
    private String urlPatterns;

    @Bean
    @ConditionalOnProperty(value = "xss.enabled",havingValue = "true") //条件属性,获取值,里面有“true”怎生效
    public FilterRegistrationBean xssFilterRegistration(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //设置dispatcher类型
        registrationBean.setDispatcherTypes(DispatcherType.REQUEST);
        //设置过滤器
        registrationBean.setFilter(new XssFilter());
        //增加匹配访问链接
        registrationBean.addUrlPatterns(StringUtils.split(urlPatterns,","));
        //设置过滤器名称
        registrationBean.setName("xssFilter");
        //设置过滤器优先级(xss过滤器为最高)
        registrationBean.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);

        //设置初始化参数
        Map<String,String> initParameters = new HashMap<String,String>();
        initParameters.put("excludes",excludes);
        registrationBean.setInitParameters(initParameters);

        return registrationBean;
    }
}


//过滤器实现类
public class XssFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(XssFilter.class);

    /*排除链接*/
    public List<String> excludes = new ArrayList<>();

    /*初始化filter*/
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Xss Filter init");

        //拿到FilterConfig中初始参数
        String tempExcludes = filterConfig.getInitParameter("excludes");
        if (StringUtils.isNotEmpty(tempExcludes)){
            String[]urls =tempExcludes.split(",");
            for (int i =0; urls != null && i<urls.length;i++){
                excludes.add(urls[i]);
            }
        }

    }

    /*执行过滤*/
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        logger.info("Xss Filter doFilter");
        /*
        * 判断是否有xss,没有直接放行;有的话处理一下。
        * */
        if (handleExcludeURL(req,resp)){
            chain.doFilter(request,response);
            return;
        }
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest)request);
        chain.doFilter(xssRequest,response);
    }

    /*销毁*/
    @Override
    public void destroy() {
        logger.info("Xss Filter init");
    }

    /*是否包含排除链接*/
    private boolean handleExcludeURL(HttpServletRequest request,HttpServletResponse response){
        String url = request.getServletPath();
        String method = request.getMethod();
        if (method == null || method.matches("GET") || method.matches("DELETE")){
            return true;
        }
        return StringUtils.matches(url,excludes);
    }
}

//请求体过滤
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XssHttpServletRequestWrapper(HttpServletRequest request){super(request);}

    @Override
    public String[] getParameterValues(String name){
        String [] values = super.getParameterValues(name);
        if (values != null){
            int length = values.length;
            String [] escapseValues = new String[length];
            for (int i = 0; i < length; i++){
                //防止xss攻击和过滤前后空格
                escapseValues[i] = EscapeUtil.clean(values[i].trim());
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }
}

//工具类
public class EscapeUtil {
    public static String clean(String content){
        return new HTMLFilter().filter(content);
    }
}

//底层实现过滤功能的类
//hutools
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>5.7.11</version>
</dependency>
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202301/5282.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者