maven依赖
点击查看代码
<!-- 防xss攻击 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
拦截修改请求字段工具类
点击查看代码
/**
* @Description: xss非法标签过滤
*/
public class XssFilterUtil {
public static String clean(String content) {
return Jsoup.clean(content, Whitelist.none());
}
}
包装类
点击查看代码
/**
* @Description: 使用HttpServletRequestWrapper重新封装request参数
*/
public class XSSRequestWrapper extends HttpServletRequestWrapper {
/**
* 构造方法
*/
public XSSRequestWrapper(HttpServletRequest request) {
super(request);
}
/**
* 处理参数值
*/
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = dealString(values[i]);
}
return encodedValues;
}
@Override
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
return dealString(value);
}
@Override
public String getHeader(String name) {
String value = super.getHeader(name);
return dealString(value);
}
/**
* 字符串处理
*/
private String dealString(String value) {
if (value != null) {
// 采用spring的StringEscapeUtils工具类 实现
value = XssFilterUtil.clean(value);
}
return value;
}
}
XSS过滤器
点击查看代码
/**
* @Description: 拦截防止注入漏洞(即防止XSS的跨站脚本攻击)
*/
public class XssFilter implements Filter {
private FilterConfig filterConfig = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}
@Override
public void destroy() {
this.filterConfig = null;
}
}
配置过滤器生效地址
点击查看代码
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean XssFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean(new XssFilter());
registration.addUrlPatterns("/*");
return registration;
}
}