Java Spring | Verifying against WhiteList IP Addresses (spring 4.0.4)

| By Webner

While designing RESTful web services in a Spring-based web application, we may have a requirement that some web services should be allowed to run only from specific IP addresses. Spring framework provides a simple procedure to verify if the incoming IP address in available in the whiteList Address list or not.

Following are the steps that we have to follow to achieve our goal:

Step1: Create an annotation which should be available for reflections at runtime:

public @interface RestrictIp {
}@RequestMapping( value ="test" ,method = RequestMethod.POST ,produces = "application/json", headers = "Accept=application/json"  )
@ResponseBody TestRequest cardUpdate(@RequestBody(required=false) String  request) 
//return response;

Step2: Define a spring interceptor and apply the check to a whitelist IP address:

package com.test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import antlr.collections.List;
public class  RestrictAccessInterceptor extends HandlerInterceptorAdapter{
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod)handler;
if (method.getMethodAnnotation(RestrictIp.class)!=null) {
//add your ip check here. This will execute only for those classes  Having RestrictIp annotation.
return accessAllowed;

The above code in bold will execute only for those methods having RestrictIp annotation. Inside this you , an check the incoming IP address and can decide whether to allow it or not.

Step 3: Add your interceptor inside applicationContext.xml file: Demo applicationContext.xml:

<beans xmlns=""
xmlns:mvc="" xmlns:xsi=""
<context:component-scan base-package="," />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:mapping path="/**" />
//your interceptor class complete path here
<bean class="com.test.RestrictAccessInterceptor">
<context:component-scan base-package="com.test" />

Leave a Reply

Your email address will not be published. Required fields are marked *