Yarik Soltys
Yarik Soltys

Reputation: 325

How to do that service wriiten in java can handle requests only from the defined ip?

I want to write application in java that consists of few endpoints. I want that this endpoints handle requests only if They are sent from defined ip. How can I implement it?

Upvotes: 0

Views: 100

Answers (2)

Sujit kumar
Sujit kumar

Reputation: 131

Web Application

Apache Tomcat

Edit the WEB-INF/web.xml file in the application. Add the following:

<filter>
  <filter-name>Remote Address Filter</filter-name>
  <filter-class>org.apache.catalina.filters.RemoteAddrFilter</filter-class>
  <init-param>
    <param-name>allow</param-name>
    <param-value><!-- insert your ip list / regex here --></param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>Remote Address Filter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

This instructs the filter to block all IP addresses except the ones included. The filter supports blocking only the IP addresses listed. More information on the filter can be found here.

Spring Boot

For Spring Boot applications that run with the embedded Apache Tomcat container, which is the default behavior, use the same filter described in the Apache Tomcat section above. It is configured in the code instead of XML. The Spring Boot document explains how to enable a Servlet Filter. Use the instructions in the document to enable the RemoteAddrFilter.

Spring Boot Document : Document

Upvotes: 1

Ali Azim
Ali Azim

Reputation: 180

Do something like this to get the IP address, that matches this address with your predefined IP addresses.

@RequestMapping(value = "startup", method = RequestMethod.GET)
public @ResponseBody ProcessResponse startUp(@RequestBody RequestTemplate requestTemplate, HttpServletRequest request) {

        System.out.println(request.getRemoteAddr());
        // some other code
}

Upvotes: 1

Related Questions