通过在项目中自定义一个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() {
}
}