我需要隐藏来自与特定 IP 不同的 IP 的请求的特定 API。 例如,如果我尝试使用它并且我的 IP 是 192.168.1.1,那么这应该可以工作,但如果我的 IP 是 192.168.1.2,则不行。
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
@IpRestricted
public void download(@PathVariable("id") String id) {
...
}
我读到我可以让它创建一个特定的注释,在本例中我称之为“@IpRestricted”,但是我该如何继续呢?有更好的解决方案吗?
最佳答案
然后我意识到我可以在不使用 spring security 的情况下完成它。 我做了这样的注释:
@Retention(RetentionPolicy.RUNTIME)
public @interface IpRestricted {
}
然后我检查 HandlerInterceptor preHandle 方法中的请求 IP 地址:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod)handler;
if (method.getMethodAnnotation(IpRestricted.class)!=null) {
if (!request.getRemoteAddr().equals("192.168.1.1")) {
throw new UnauthorizedException("Ip not authorized");
}
}
}
[....]
}
下载方法:
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
@IpRestricted
public void download(@PathVariable("id") String id) {
...
}
就是这样!
关于java - Spring MVC : IP restriction for a single controller method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32581659/