Question

I knew that I can add a Valve in context.xml in tomcat server to allow or deny some IP address :

<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.0\.0\.1" denyStatus="403" />

Except above configuration, Are there any other method that I can config IP restriction?

For example, can I use text file or database to store IP addresses for IP restriction propose?

Thank you very much!!!

Was it helpful?

Solution

You can dynamically register Tomcat's Remote Address Filter.

http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Remote_Address_Filter

It looks like this:

@WebListener
public class MyServletContextListener implements ServletContextListener {
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    // Get IP addresses from the DB or text file.
    ...

    ServletContext sc = sce.getServletContext();
    FilterRegistration fr;
    fr = sc.addFilter("RemoteAddrFilter", "org.apache.catalina.filters.RemoteAddrFilter");
    fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    fr.setInitParameter("allow", "127\\.0\\.0\\.1");
    fr.setInitParameter("denyStatus", "403");
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top