fix: 校验origin, 有些socket请求不安全

This commit is contained in:
CaptainB 2023-10-13 14:17:59 +08:00 committed by 刘瑞斌
parent 466ca2fb3e
commit 1004753a48
1 changed files with 25 additions and 3 deletions

View File

@ -37,6 +37,12 @@ public class CsrfFilter extends AnonymousFilter {
if (ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) {
return true;
}
// 校验 referer
validateReferer(httpServletRequest);
// 校验 origin
validateOrigin(httpServletRequest);
// websocket 不需要csrf
String websocketKey = httpServletRequest.getHeader("Sec-WebSocket-Key");
if (StringUtils.isNotBlank(websocketKey)) {
@ -47,11 +53,27 @@ public class CsrfFilter extends AnonymousFilter {
String csrfToken = httpServletRequest.getHeader(TOKEN_NAME);
// 校验 token
validateToken(csrfToken);
// 校验 referer
validateReferer(httpServletRequest);
return true;
}
private void validateOrigin(HttpServletRequest httpServletRequest) {
Environment env = CommonBeanFactory.getBean(Environment.class);
String domains = env.getProperty("origin.urls");
if (StringUtils.isBlank(domains)) {
// 没有配置不校验
return;
}
String[] split = StringUtils.split(domains, ",");
String origin = httpServletRequest.getHeader(HttpHeaders.ORIGIN);
if (split != null) {
if (!ArrayUtils.contains(split, origin)) {
throw new RuntimeException("csrf origin error");
}
}
}
private void validateReferer(HttpServletRequest request) {
Environment env = CommonBeanFactory.getBean(Environment.class);
String domains = env.getProperty("referer.urls");
@ -64,7 +86,7 @@ public class CsrfFilter extends AnonymousFilter {
String referer = request.getHeader(HttpHeaders.REFERER);
if (split != null) {
if (!ArrayUtils.contains(split, referer)) {
throw new RuntimeException("csrf error");
throw new RuntimeException("csrf referer error");
}
}
}