Java Web使用過濾器防止Xss攻擊,解決Xss漏洞
阿新 • • 發佈:2018-12-20
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 { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //使用包裝器 XssFilterWrapper xssFilterWrapper=new XssFilterWrapper((HttpServletRequest) servletRequest); filterChain.doFilter(xssFilterWrapper,servletResponse); } @Override 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); } /** * 對陣列引數進行特殊字元過濾 */ @Override 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方法轉義的,方便很多