Friday, January 20, 2012

IP request filtering in JBoss and Tomcat

I just needed to allow only particular IPs to have access to a servlet or web app and was somehow surprised IP filtering of requests is not part of the standards. The portable way of doing so is to write a custom filter [1] [2] but this is not something I want to bother with.
Fortunately JBoss AS has this capability OOB being based on Apache Tomcat which has a valve to help with that [3]. update: Wildfly, the JBoss AS new name will be using undertow as the servlet and web server engine so this won't work on it.

In short you can create a file WEB-INF/context.xml for JBoss or see docs [4] for Tomcat with content like:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="192.168.*,142.104.128.*"/>
</Context>

[1] http://www.roseindia.net/servlets/ip-filter-example.shtml
[2] http://stackoverflow.com/questions/2869623/how-to-block-a-ip-address-using-web-xml
[3] http://hcmc.uvic.ca/blogs/index.php?blog=30&p=2658&more=1&c=1&tb=1&pb=1 - I've started here and saved me lots of time
[4] http://tomcat.apache.org/tomcat-5.5-doc/config/context.html