package com.ruoyi.web.controller.hanler;
|
|
import com.ruoyi.common.annotation.IpWhitelist;
|
import com.ruoyi.system.domain.SysConfig;
|
import com.ruoyi.system.mapper.SysConfigMapper;
|
import org.apache.commons.net.util.SubnetUtils;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.http.HttpStatus;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.method.HandlerMethod;
|
import org.springframework.web.servlet.HandlerInterceptor;
|
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
import java.util.ArrayList;
|
import java.util.Arrays;
|
import java.util.List;
|
|
@Component
|
public class IpWhitelistInterceptor implements HandlerInterceptor {
|
@Autowired
|
private SysConfigMapper sysConfigMapper;
|
|
@Override
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
System.out.println("处理器类: " + handler.getClass().getName());
|
if (handler instanceof HandlerMethod) {
|
HandlerMethod handlerMethod = (HandlerMethod) handler;
|
if (handlerMethod.hasMethodAnnotation(IpWhitelist.class)) {
|
//获取请求的IP,判断是不是在白名单中
|
String clientIp = getClientIp(request);
|
if (!isIpInWhitelist(clientIp)) {
|
response.setStatus(HttpStatus.FORBIDDEN.value());
|
response.getWriter().write("Access denied: IP address not whitelisted");
|
return false;
|
}
|
}
|
}
|
return true;
|
}
|
|
private String getClientIp(HttpServletRequest request) {
|
String ip = request.getHeader("X-Forwarded-For");
|
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("Proxy-Client-IP");
|
}
|
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("WL-Proxy-Client-IP");
|
}
|
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getRemoteAddr();
|
}
|
return ip;
|
}
|
|
private boolean isIpInWhitelist(String ip) {
|
try {
|
SysConfig config = new SysConfig();
|
config.setConfigKey("sys.ip.whitelist");
|
SysConfig sysConfig = sysConfigMapper.selectConfig(config);
|
List<String> whitelistIps = Arrays.asList(sysConfig.getConfigValue().split(","));
|
for (String whitelist : whitelistIps) {
|
if (whitelist.contains("/")) {
|
// CIDR格式
|
SubnetUtils subnetUtils = new SubnetUtils(whitelist);
|
if (subnetUtils.getInfo().isInRange(ip)) {
|
return true;
|
}
|
} else {
|
// 单个IP
|
if (whitelist.equals(ip)) {
|
return true;
|
}
|
}
|
}
|
} catch (Exception e) {
|
return false;
|
}
|
return false;
|
}
|
}
|