拦截器设置ip白名单
时间: 2024-06-13 16:07:29 浏览: 174
ip黑白名单拦截器java示例
拦截器可以用来实现IP白名单的功能,具体步骤如下:
1. 创建一个拦截器类,实现HandlerInterceptor接口,并在preHandle方法中进行IP白名单校验。代码示例:
```java
public class IPWhiteListInterceptor implements HandlerInterceptor {
private List<String> whiteList = Arrays.asList("127.0.0.1", "192.168.0.1"); // IP白名单列表
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String ip = request.getRemoteAddr(); // 获取客户端IP地址
if (whiteList.contains(ip)) { // 如果客户端IP在白名单列表中,则放行
return true;
} else { // 否则返回403错误
response.sendError(HttpServletResponse.SC_FORBIDDEN, "IP地址不在白名单中");
return false;
}
}
}
```
2. 在WebMvcConfigurer的addInterceptors方法中注册拦截器,并指定拦截规则。代码示例:
```java
@Configuration
public class IPWhiteListWebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPWhiteListInterceptor())
.addPathPatterns("/**"); // 拦截所有请求
}
}
```
3. 在需要进行IP白名单校验的Controller方法上添加自定义注解,并在拦截器中获取注解配置信息进行校验。代码示例:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IPWhiteList {
String[] value() default {}; // IP白名单列表
}
public class IPWhiteListInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
IPWhiteList annotation = handlerMethod.getMethodAnnotation(IPWhiteList.class);
if (annotation != null) { // 如果方法上有IPWhiteList注解,则进行IP白名单校验
String[] whiteList = annotation.value();
String ip = request.getRemoteAddr();
if (Arrays.asList(whiteList).contains(ip)) {
return true;
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "IP地址不在白名单中");
return false;
}
}
}
return true;
}
}
@RestController
public class UserController {
@GetMapping("/user")
@IPWhiteList({"127.0.0.1", "192.168.0.1"}) // 添加IPWhiteList注解
public String getUser() {
return "user";
}
}
```
阅读全文