聊聊Spring boot项目中IP白名单限制
在Spring Boot项目中实现IP白名单限制,可以通过定义一个拦截器来检查每个请求的IP地址是否在白名单内。以下是一个简单的实现示例:
- 创建一个拦截器类
IPWhitelistInterceptor
:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Arrays;
import java.util.List;
public class IPWhitelistInterceptor implements HandlerInterceptor {
private List<String> whitelist;
public IPWhitelistInterceptor(String... whitelist) {
this.whitelist = Arrays.asList(whitelist);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String ip = request.getRemoteAddr();
if (whitelist.contains(ip)) {
return true; // 在白名单内,继续处理请求
} else {
response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 返回403禁止访问
return false;
}
}
}
- 注册拦截器。在Spring Boot配置类中添加拦截器:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 假设白名单是一组静态定义的IP地址
String[] whiteList = new String[]{"192.168.1.1", "192.168.1.2"};
registry.addInterceptor(new IPWhitelistInterceptor(whiteList)).addPathPatterns("/**");
}
}
这样配置后,只有来自白名单内IP地址的请求被允许访问,其他请求会被拦截并返回403 Forbidden响应。
评论已关闭