简体   繁体   中英

Spring MVC: IP restriction for a single controller method

I need to hide a specific API for requests coming form IP different to a specific one. For instance this should work if I try to use it and my IP is 192.168.1.1, but not if my IP is 192.168.1.2.

@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
@IpRestricted
public void download(@PathVariable("id") String id) {
  ...
}

I read I can make it creating a specific annotation, the one I called "@IpRestricted" in this example, but than how can I proceed? There are better solution to this?

I then realized I can make it without using spring security. I made an annotation like this:

@Retention(RetentionPolicy.RUNTIME)
public @interface IpRestricted {
}

Than I check the request IP address inside a HandlerInterceptor preHandle method:

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");
            }
        }
    }
    [....]
}

And for the download method:

@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
@IpRestricted
public void download(@PathVariable("id") String id) {
   ...
}

That's it!

I think the best Spring solution available for this case is the hasIpAddress() method from Spring Security . There are many different ways to configure permissions to your services via Spring Security, and the IP-based solution is also implemented.

Here is a good example of how to set it up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM