Java SpringMVC:单控制器方法的IP限制
我需要为来自不同IP的请求隐藏一个特定的API。 例如,如果我尝试使用它,并且我的IP是192.168.1.1,那么它应该可以工作,但是如果我的IP是192.168.1.2,那么它就不能工作Java SpringMVC:单控制器方法的IP限制,java,api,spring-mvc,spring-security,Java,Api,Spring Mvc,Spring Security,我需要为来自不同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) { ...
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
@IpRestricted
public void download(@PathVariable("id") String id) {
...
}
我读到我可以创建一个特定的注释,在本例中我称之为“@IpRestricted”,但是如何继续?有更好的解决方案吗?我认为对于这种情况,最好的Spring解决方案是Spring Security中的
hasIpAddress()
方法。有许多不同的方法可以通过Spring Security配置对服务的权限,并且还实现了基于IP的解决方案
是如何设置它的一个很好的例子。然后我意识到我可以不用使用spring security来设置它。 我做了这样一个注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface IpRestricted {
}
然后在HandlerInterceptor预处理方法中检查请求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) {
...
}
就这样 在SpringSecurity中,我看到我也可以使用,但我仍然不明白应该把它放在哪里……你有两个选择。您可以使用注释(例如:@PreAuthorize(“hasIpAddress('127.0.0.1')”),或者将“security.xml”放在一起配置文件。我导入了spring安全依赖项,并在控制器方法中添加了注释@PreAuthorize,但它似乎工作不正常,我认为spring安全性不工作的最常见原因是过滤器根本没有注册。请检查此项:。它可以工作,是的。spring安全性是一个灵活的库,但作为库它显然更复杂。如果您不打算在此应用程序中对身份验证进行进一步改进,那么使用自制的批注完全可以。这两项检查的目的是什么?
If(handler instanceof HandlerMethod)
和If(method.getMethodAnnotation(IpRestricted.class)!=null)
?在哪些情况下,这些检查将为false
?首先告诉您对象是否将成为处理您的请求的方法。如果“download()”中不存在注释IpRestrictred,则第二个可以为null方法注释。例如,如果您不希望所有方法都受到ip的限制,您将仅在需要注释的方法上配置注释。谢谢!如果(handler instanceof HandlerMethod)中的HandlerMethod
,还有什么可以代替if中的HandlerMethod
?例如,它可以是org.springframework.web.socket.server.support.websockethtprequestHandler