How to log IP addresses of incoming requests to a Spring Boot app in a centralized way?

Let’s say you want to track the source of hits coming to your REST services.

And you have developed them using Spring Boot.

Here is the algorithm:

STEP1: Create a Spring Handler Interceptor

STEP2: Retrieve the IP address in the prehandle method of the Handler interceptor.

2.a) Use X-Forwarded-For header extracted from HttpRequest object to find the IP address of the client

2.b) If it is not present , retrieve it from the request object itself

STEP3: Register the interceptor

Advertisements

Here is the Spring Interceptor :

package com.ipaddress.demo;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class IPAddressInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String ipAddress = request.getHeader("X-Forward-For");

        if(ipAddress== null){

            ipAddress = request.getRemoteAddr();
        }

        System.out.println(ipAddress);
        return false;
    }
}

We get the IP address from the X-Forward-For header because it contains the actual ip address of the client in case if it requests through a proxy. The proxy address will not be passed through in this case in this header.

If it is not present we can retrieve it from the request object itself . Instead of printing it out as I have shown above we can log it for tracking in live environment.

Once the interceptor is created we need to register it:

package com.ipaddress.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class InterceptorRegistry implements WebMvcConfigurer {

    @Autowired
    private IPAddressInterceptor ipAddressInterceptor;
    @Override
    public void addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry registry) {

        registry.addInterceptor(ipAddressInterceptor);
    }
}


That’s it.

Now when you hit any of the REST services in your app ,the IP address of the source of the hit will be tracked .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s