SpringBoot安全验证之Referer拦截器 发表于 2019-03-17 | 分类于 springboot 自定义Referer拦截器12345678910111213141516171819202122232425262728293031323334353637383940public class RefererInterceptor extends HandlerInterceptorAdapter { // URL匹配器 private AntPathMatcher matcher = new AntPathMatcher(); @Autowired private RefererProperties properties; @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception { String referer = req.getHeader("referer"); String host = req.getServerName(); // 只验证POST请求 if ("POST".equals(req.getMethod())) { if (referer == null) { // 状态置为404 resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return false; } java.net.URL url = null; try { url = new java.net.URL(referer); } catch (MalformedURLException e) { // URL解析异常,也置为404 resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return false; } // 首先判断请求域名和referer域名是否相同 if (!host.equals(url.getHost())) { // 如果不等,判断是否在白名单中 if (properties.getRefererDomain() != null) { for (String s : properties.getRefererDomain()) { if (s.equals(url.getHost())) { return true; } } } return false; } } return true; }} 配置白名单Referer域名1234567@Component@ConfigurationProperties(prefix = "referer")public class RefererProperties { // 白名单域名 private List<String> refererDomain; //setter,getter方法} yml配置12345referer: refererDomain: - baidu.com - pibigstar.com - mxspvip.cn -------------本文结束感谢您的阅读-------------