Java接口以注解的形式判断访问是否来自内网的示例,不是来自内网的不允许访问
时间: 2024-05-03 18:20:27 浏览: 94
可以使用Spring框架的@RequestHeader注解获取请求头信息,在拦截器中根据请求头信息判断是否来自内网。以下是示例代码:
```
@Component
public class InternalNetworkInterceptor extends HandlerInterceptorAdapter {
@Autowired
private InetAddress internalNetwork;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String remoteAddr = request.getRemoteAddr();
if (internalNetwork.getHostAddress().equals(remoteAddr)) {
return true;
} else {
response.setStatus(HttpStatus.FORBIDDEN.value());
return false;
}
}
}
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/test")
@InternalNetworkAllowed
public String test() {
return "Hello World!";
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InternalNetworkAllowed {
}
```
在@InternalNetworkAllowed注解中标注可以来自内网的请求,然后在拦截器中进行判断,不符合条件的请求返回403 Forbidden。其中InetAddress internalNetwork可以在配置文件中配置为内网IP地址。
阅读全文