简体   繁体   中英

URL access controll by IP in Tomcat7

I need to control URL access according to client IP on tomcat 7.0.39 This is what I found http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Remote_Address_Filter

but I can't understand all from it. Do you have any additional examples, totorials etc.

what I actually need is to allow all IPs access, eg. "http://base_url/a/b/c" and allow localhost/127.0.0.1 access "http://base_url/a"

I couldn't understand how to match "any" IP or if i need multiple filters or multiple entries within the filter.

Thanks.

In fact, you need protect only /base_url/a , since other addresses are opened to all IPs. Define 2 filters. First to allow local access by IP, second by localhost:

<filter>
  <filter-name>RemoteAddressFilter</filter-name>
  <filter-class>org.apache.catalina.filters.RemoteAddrFilter</filter-class>
  <init-param>
    <param-name>allow</param-name>
    <param-value>127.0.0.1|::1|0:0:0:0:0:0:0:1</param-value>
  </init-param>
  <init-param>
    <param-name>deny</param-name>
    <param-value>192\.\d+\.\d+\.\d+</param-value>
  </init-param>   
</filter>
<filter-mapping>
  <filter-name>RemoteAddressFilter</filter-name>
  <url-pattern>/a/*</url-pattern>
</filter-mapping>


<filter>
  <filter-name>RemoteHostFilter</filter-name>
  <filter-class>org.apache.catalina.filters.RemoteHostFilter</filter-class>
  <init-param>
    <param-name>allow</param-name>
    <param-value>localhost</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>RemoteHostFilter</filter-name>
  <url-pattern>/a/*</url-pattern>
</filter-mapping>

If the filter you are writing doesn't work the way you are expecting to, you could always implement your own using the javax.servlet.Filter API ( http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html ).

There are a couple examples here:

Writing a Servlet Filter is straightforward and you can make it achieve more than just IP filtering.

Thank you all,

Eventually I created my own filter this is how:

  • create class that extends BaseFilter and implament doFilter.
  • required jar files: catalina.jar, servlet_api.jar, tomcat_juli.jar
  • in the do filter running chain.doFilter means continue filter this connection (or use it if no more filters exists)
  • an init method can also be used to read params from web.xml (where you put the filter configuration)
  • add your new jar (with the filter to Tomcat's lib directory) add the jar name to Tomcat/conf/catalina.properties default jar scanner

BR.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM