liusheng
6 天以前 b5d8fe9ffa3f665709247055441da4d9fa95ce9a
ruoyi-admin/src/main/java/com/ruoyi/web/controller/hanler/IpWhitelistInterceptor.java
@@ -5,7 +5,6 @@
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;
@@ -13,9 +12,9 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
@Component
public class IpWhitelistInterceptor implements HandlerInterceptor {
@@ -61,17 +60,8 @@
            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)) {
                if (isInRange(ip, whitelist)) {
                        return true;
                    }
                } else {
                    // 单个IP
                    if (whitelist.equals(ip)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
@@ -79,4 +69,53 @@
        }
        return false;
    }
    /**
     * 智能验证IP是否在指定的模式内
     * 支持:CIDR格式、通配符格式、单个IP
     */
    public boolean isInRange(String ip, String pattern) {
        if (pattern == null || ip == null) {
            return false;
        }
        // 1. 如果是CIDR格式(包含/)
        if (pattern.contains("/")) {
            try {
                SubnetUtils utils = new SubnetUtils(pattern);
                return utils.getInfo().isInRange(ip);
            } catch (IllegalArgumentException e) {
                return false;
            }
        }
        // 2. 如果是通配符格式(包含*)
        if (pattern.contains("*")) {
            return matchesWildcardPattern(ip, pattern);
        }
        // 3. 如果是单个IP地址
        if (isValidIp(pattern)) {
            return ip.equals(pattern);
        }
        return false;
    }
    /**
     * 通配符模式匹配
     */
    private boolean matchesWildcardPattern(String ip, String wildcardPattern) {
        // 将通配符转换为正则表达式
        String regex = wildcardPattern.replace(".", "\\.").replace("*", "\\d+");
        return Pattern.matches(regex, ip);
    }
    /**
     * 验证是否为合法IP地址
     */
    private boolean isValidIp(String ip) {
        return Pattern.matches("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$", ip);
    }
}