Amit Patel
Amit Patel

Reputation: 37

How to send Ip address of caller in spring RestTemplate

We are planning to separate our UI code from our spring restful apis as we want ui to be customized for different clients. We have a rest api which authenticates user against username and password provided. Actually in my UI package i have a spring controller which calls this api to get the user authenticated with spring RestTemplate and returns appropriate page depending on the outcome. The authentication api uses the IP address from the request and blocks the IP address for 24 hours if someone provides wrong username password three times. But the issue is every time i call this api it gets my server's IP address where my UI package is deployed and i guess this is correct behavior as the caller is my UI server. So is there a way i can get the IP address of caller on my UI package and set it to the request which I make to my api. Is there a way i can set actual caller's IP in RestTemplate request.

Upvotes: 1

Views: 4056

Answers (1)

Raju Sharma
Raju Sharma

Reputation: 2516

You can do it using HttpServletRequest, your api method should have parameter defined for HttpServletRequest.

Your api method should look like:

 @RequestMapping(value = "/myApiPath", method = RequestMethod.GET)
          public void myApiMethod(MyObject myobject, final HttpServletRequest request) throws IOException {
                String ipAddress=getIpAddressOfRequest(request); // get Ip address
          }

And then use HttpServletRequest request for getting ip address, as below:

public static String getIpAddressOfRequest(final HttpServletRequest request) {
            String remoteAddr = "";
            if (request != null) {
                remoteAddr = request.getHeader("X-FORWARDED-FOR");
                if (remoteAddr == null || "".equals(remoteAddr)) {
                    remoteAddr = request.getRemoteAddr();
                }
            }
            return remoteAddr;
      }

And even you can have your condition on domain name, by getting server name using below code:

public static String getProtocolHostnameAndPort(final HttpServletRequest request) {
            String protocol = request.getProtocol().split("/")[0].toLowerCase();
            String hostname = request.getServerName();
            int port = request.getServerPort();
            StringBuilder result = new StringBuilder(protocol + "://" + hostname);
            if (port != 80) {
                  result.append(":").append(port);
            }
            return result.toString();
      }

Upvotes: 1

Related Questions