springboot 集成IP白名单配置
添加白名单黑名单的目的是控制请求
使用拦截器或者过滤器都是可以的!
以下主要是使用拦截器(Interceptor)
1.先要能获取到IP,所以需要一个ip工具类
public class IPUtils {/*** 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值* @return ip*/public static String getRealIP(HttpServletRequest request) {String ip = request.getHeader("x-forwarded-for");if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {// 多次反向代理后会有多个ip值,第一个ip才是真实ipif( ip.indexOf(",")!=-1 ){ip = ip.split(",")[0];}}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");System.out.println("Proxy-Client-IP ip: " + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");System.out.println("WL-Proxy-Client-IP ip: " + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");System.out.println("HTTP_CLIENT_IP ip: " + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("X-Real-IP");System.out.println("X-Real-IP ip: " + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();System.out.println("getRemoteAddr ip: " + ip);}return ip;}
}
2.创建一个拦截器去实现拦截,这里我想的是从配置文件读取,常规的@value是无法直接获取到的,所以需要先通过注解@Compont实现拦截器注册给spring管理,再通过set的办法赋值
public class IPInterceptor implements HandlerInterceptor {private static String ipWhite;@Value("${ip.white}")public void setIpWhite(String ipWhite) {IPInterceptor.ipWhite = ipWhite;}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println(ipWhite);if(StringUtils.isBlank(ipWhite)) return true;//全部不拦截String[] split = {};if(ipWhite.contains(",")){split = ipWhite.split(",");}else {split = new String[]{ipWhite};}List<String> list = Arrays.asList(split);//获取请求的IPString realIP = IPUtils.getRealIP(request);if(!list.contains(realIP))return false; //非指定IP 拦截不通过return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {HandlerInterceptor.super.afterCompletion(request, response, handler, ex);}
}
3.最后一步也是最关键的一步,让我们的拦截器生效是要把拦截器注册进来
@Configuration //拦截器注册进来
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new IPInterceptor()).addPathPatterns("/test/*");}
}