SpringBoot安全验证之Referer拦截器

自定义Referer拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public 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域名

1
2
3
4
5
6
7
@Component
@ConfigurationProperties(prefix = "referer")
public class RefererProperties {
// 白名单域名
private List<String> refererDomain;
//setter,getter方法
}

yml配置

1
2
3
4
5
referer:
refererDomain:
- baidu.com
- pibigstar.com
- mxspvip.cn
-------------本文结束感谢您的阅读-------------