0

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!!!

Timmy Lo
  • 43
  • 10

1 Answers1

3

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");
  }
}
Shinichi Kai
  • 4,415
  • 2
  • 21
  • 25
  • Thank you for your response!!, May I know After I built up this class, How to call this class in context.xml???? – Timmy Lo Jul 08 '13 at 08:30
  • To make the above class work you need Tomcat 7 but you do not need any configuration changes. The above class implements [ServletContextListener](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html) and is annotated with [@WebListener](http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebListener.html). Tomcat automatically detects the class and calls contextInitialized on the webapp startup. – Shinichi Kai Jul 08 '13 at 08:54
  • Thanks again! Which/Where the file I need to modify actually to add the class **MyServletContextListener** ? is it **bootstrap.jar** in ***C:\tomcat\bin\*** ? – Timmy Lo Jul 08 '13 at 09:15
  • or I only need to create a jar file which include the class `MyServletContextListener` and then put the jar to c:\tomcat\bin ? – Timmy Lo Jul 08 '13 at 09:20
  • No, you need to put the class into your webapp (Just like a servlet class). – Shinichi Kai Jul 08 '13 at 09:23
  • Is it means that I should put the class into `C:\tomcat\webapps\myapps\WEB-INF\lib`? Thanks! you save my life!! – Timmy Lo Jul 09 '13 at 03:55
  • You'd be better off putting the class into `WEB-INF/classes`. – Shinichi Kai Jul 09 '13 at 04:05
  • may I know @WebListener is only support tomcat 7? – Timmy Lo Jul 09 '13 at 04:25
  • `@Weblistner` is part of Servlet 3.0. [Only Tomcat 7 supports Servlet 3.0](http://tomcat.apache.org/whichversion.html). – Shinichi Kai Jul 09 '13 at 04:30