跨站请求伪造解决办法之——过滤referer
当然,referer也是可以伪造的,Http请求本身就没有不能伪造的东西。
所以本方法只能在一定程度上防止非法请求,仅供参考。
项目的web.xml中增加过滤器:
<filter> <filter-name>RefererFilter</filter-name> <filter-class>com.sdyy.common.filters.RefererFilter</filter-class> </filter> <filter-mapping> <filter-name>RefererFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
项目中增加RefererFilter类:
package com.sdyy.common.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RefererFilter extends HttpServlet implements Filter { private static final long serialVersionUID = 1L; private FilterConfig filterConfig; public void init(FilterConfig config) { this.filterConfig = config; } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // 链接来源地址 String referer = request.getHeader("referer"); if (referer == null || !referer.contains(request.getServerName())) { /** * 如果 链接地址来自其他网站,则返回错误页面 */ request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } else { chain.doFilter(request, response); } } public void destroy() { this.filterConfig = null; } }