通過在項目中自定義一個Filter過濾器實現修復反射型xss漏洞,具體方法如下:
package com.eastrobot.robotdev.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 解決動態腳本獲取網頁cookie,將cookie設置成HttpOnly
String sessionId = req.getSession().getId();
resp.setHeader("SET-COOKIE", "JSESSIONID=" + sessionId + "; HttpOnly");
resp.setHeader("x-frame-options", "SAMEORIGIN");
chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
}
@Override
public void destroy() {
}
}