基于Spring Boot实现IP黑白名单功能
以下是一个简化的Spring Boot应用程序示例,用于实现IP黑白名单功能:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
@Configuration
public class IPFilterConfig implements WebMvcConfigurer {
// 白名单列表
private final List<String> whiteList = Arrays.asList("123.123.123.123", "456.456.456.456");
// 黑名单列表
private final List<String> blackList = Arrays.asList("789.789.789.789", "012.012.012.012");
@Bean
public IPFilterInterceptor ipFilterInterceptor() {
return new IPFilterInterceptor(whiteList, blackList);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(ipFilterInterceptor())
.addPathPatterns("/**") // 拦截所有路径
.order(1);
}
public static class IPFilterInterceptor implements HandlerInterceptor {
private final List<String> whiteList;
private final List<String> blackList;
public IPFilterInterceptor(List<String> whiteList, List<String> blackList) {
this.whiteList = whiteList;
this.blackList = blackList;
}
@Override
public boolean preHandle(HttpServletRequest request, Object handler) {
String ip = request.getRemoteAddr();
if (blackList.contains(ip)) {
return false; // 如果在黑名单中,则不处理请求
}
if (!whiteList.isEmpty() && !whiteList.contains(ip)) {
return false; // 如果不在白名单且白名单不为空,则不处理请求
}
return true; // 允许请求继续
}
}
}
这段代码定义了一个IPFilterConfig配置类,实现了WebMvcConfigurer接口,并注册了一个自定义的拦截器IPFilterInterceptor。在preHandle方法中,它检查请求的IP地址是否在黑名单或白名单中。如果在黑名单中,则拦截请求;如果不在白名单且白名单不为空,也会拦截请求;否则,允许请求继续。这个简单的例子展示了如何在Spring Boot应用程序中实现IP黑白名单功能。
评论已关闭