Recipe 19.10 Blocking IP Addresses with a Filter


Problem

You want to use a filter that checks the IP address associated with the request.

Solution

Use a filter that calls the HttpServletRequest 's getRemoteAddr( ) method inside the doFilter( ) method and blocks the request by not calling chain.doFilter( ) .

Discussion

A typical use of a filter in a web application is to check the request to make sure it's acceptable. Let's say your security division has discovered that a certain range of IP addresses represent nasty clients ”you want to rebuff those folks with a "403 Forbidden" HTTP response.

Example 19-16 blocks any client IP address beginning with "192.168."

Example 19-16. A filter for blocking a certain range of IP addresses
 package com.jspservletcookbook; import java.io.IOException;  import java.util.StringTokenizer;  import javax.servlet.*; import javax.servlet.http.*; public class IPFilter implements Filter {          private FilterConfig config;  public final static String IP_RANGE = "192.168";  public IPFilter( ) {}          public void  init(FilterConfig filterConfig) throws ServletException {            this.config = filterConfig;            }          public void  doFilter(ServletRequest request,        ServletResponse response,          FilterChain chain) throws IOException, ServletException {  String ip = request.getRemoteAddr( );  HttpServletResponse httpResp = null;                  if (response instanceof HttpServletResponse)             httpResp = (HttpServletResponse) response;  //Break up the IP address into chunks representing each byte         StringTokenizer toke = new StringTokenizer(ip,".");         int dots = 0;         String byte1 = "";         String byte2 = "";         String client = "";                  //         while (toke.hasMoreTokens( )){                      ++dots;                          //This token is the first number series or byte             if (dots == 1){                              byte1 = toke.nextToken( );                              } else {                              //This token is the second number series or byte                 byte2 = toke.nextToken( );                 break;//only interested in first two bytes             }         }//while                  //Piece together half of the client IP address so it can be              // compared with the forbidden range represented by        //IPFilter.IP_RANGE         client = byte1+"."+byte2;                   //if the client IP fits the forbidden range...         if (IP_RANGE.equals(client)){                      httpResp.sendError(HttpServletResponse.SC_FORBIDDEN,                             "That means goodbye forever!" );                      } else {                          //Client is okay; send them on their merry way             chain.doFilter(request,response);         }              }// doFilter  public void destroy( ){         /*called before the Filter instance is removed          from service by the web container*/     }      } 

The filter obtains the client's IP address with the ServletRequest's getRemoteAddr( ) method. The filter than parses the return value to determine if the IP address falls into the "192.168" range. If the IP address does fall into this range, then the code calls the HttpServletResponse sendError( ) method with the " 403 Forbidden" type HTTP status code, as in:

 httpResp.sendError(HttpServletResponse.SC_FORBIDDEN,   "That means goodbye forever!" ); 

This method call effectively short circuits the request by preventing the user from reaching their original destination. If the IP address is acceptable, the code calls chain.doFilter( ) , which passes the request and response objects along the filter chain. In this case, the application does not map any other filters to thanks.jsp , so the web container invokes that JSP page.

Example 19-17 shows the mapping for this filter in web.xml . The filter is mapped to all requests with the URL mapping "/*."

Example 19-17. The mapping of the IP-blocking filter
 <filter>     <filter-name>IPFilter</filter-name>     <filter-class>com.jspservletcookbook.IPFilter</filter-class> </filter>  <filter-mapping>     <filter-name>IPFilter</filter-name>     <url-pattern>/*</url-pattern> </filter-mapping>  

Figure 19-4 shows the page the web browser will display if the client IP address is blocked.

Figure 19-4. A filtered out IP address receives an HTTP Status 403 message
figs/jsjc_1904.gif

See Also

Chapter 9 on handling errors in web applications; Recipe 19.8 on using filters with RequestDispatchers ; Recipe 18.3 on using a filter to alter then forward the request; Recipe 19.1-Recipe 19.4 on mapping filters to web components ; Recipe 19.5 on configuring init parameters for a filter; Recipe 19.7 on filtering the HTTP response; Recipe 19.9 on checking form parameters with a filter.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net