转:
Java Web使用过滤器防止Xss攻击,解决Xss漏洞
版权声明:本文为博主原创文章,转载请注明出处!有时候也不是原创,手快就选了(我的文章随意转载复制,不在乎的哈!) https://blog.csdn.net/qq_31384551/article/details/83956681
web.xml添加过滤器
-
<!-- 解决xss漏洞 -->
-
<filter>
-
<filter-name>xssFilter</filter-name>
-
<filter-class>com.quickly.exception.common.filter.XssFilter</filter-class>
-
</filter>
-
<!-- 解决xss漏洞 -->
-
<filter-mapping>
-
<filter-name>xssFilter</filter-name>
-
<url-pattern>*</url-pattern>
-
</filter-mapping>
过滤器代码
-
package com.quickly.exception.common.filter;
-
-
import javax.servlet.*;
-
import javax.servlet.http.HttpServletRequest;
-
import java.io.IOException;
-
-
/**
-
* 作用:Xss过滤器
-
* 作者:Tiddler
-
* 时间:2018/11/11 10:21
-
* 类名: XssFilter
-
**/
-
public class XssFilter implements Filter {
-
-
public void init(FilterConfig filterConfig) throws ServletException {
-
-
}
-
-
-
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
-
//使用包装器
-
XssFilterWrapper xssFilterWrapper=new XssFilterWrapper((HttpServletRequest) servletRequest);
-
filterChain.doFilter(xssFilterWrapper,servletResponse);
-
}
-
-
-
public void destroy() {
-
-
}
-
}
过滤器包装器代码
-
package com.quickly.exception.common.filter;
-
-
import org.springframework.web.util.HtmlUtils;
-
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletRequestWrapper;
-
-
/**
-
* 作用:防Xss过滤器[包装器]
-
* 作者:Tiddler
-
* 时间:2018/11/11 10:20
-
* 类名: XssFilterWrapper
-
**/
-
public class XssFilterWrapper extends HttpServletRequestWrapper {
-
public XssFilterWrapper(HttpServletRequest request) {
-
super(request);
-
}
-
/**
-
* 对数组参数进行特殊字符过滤
-
*/
-
-
public String[] getParameterValues(String name) {
-
if("content".equals(name)){//不想过滤的参数,此处content参数是 富文本内容
-
return super.getParameterValues(name);
-
}
-
String[] values = super.getParameterValues(name);
-
String[] newValues = new String[values.length];
-
for (int i = 0; i < values.length; i++) {
-
newValues[i] = HtmlUtils.htmlEscape(values[i]);//spring的HtmlUtils进行转义
-
}
-
return newValues;
-
}
-
}
总结:
主要是使用Java Web的过滤器,将所有的request请求参数修改(主要是把存在xss风险的标签转义,如:<script></script>),在转义时我没有自己实现替换与转义,是直接使用的spring自带的HtmlUtils类的htmlEscape方法转义的,方便很多