HTTP Referer是header的一部分,当浏览器向web服务器发送请求的时候,会带上Referer,通过验证Referer,可以判断请求的合法性,如果Referer是其他网站的话,就有可能是CSRF攻击,则拒绝该请求。
实现方案:
1、由于可能有多个Referer允许访问,所以首先我们添加配置项
anut.allow.refererPrefixs=http://localhost,http://localhost:8087
2、验证逻辑
/** * validReferer Referer Check , 防止csrf * Created by Hoscen on 2020/10/4 15:11 * @param request * @return boolean */ public static boolean validReferer(HttpServletRequest request){ String referrer = request.getHeader("referer"); if(StringUtil.isBlank(referrer)){ return true; } String[] refererPrefixs = SystemPropertiesWithDB.getArray("anut.allow.refererPrefixs"); for(String rp : refererPrefixs){ if(referrer.lastIndexOf(rp)==0){ return true; } } return false; }
3、添加全局Interceptor
public class RefererInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 验证Referer return PermUtil.validReferer(request); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
注意:此方法不能完全防御CSRF攻击,只能说是增加了攻击的难度。