Ajax Filter : Prohibit unwanted direct access to ajax requests

The code

If we don’t want to give unwanted access to the url’s that we only need to access via ajax, we can simply do it using a Filter. Here is the code:

package net.hasnath.web.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author Md. Shamim Hasnath
 *
 */


// @WebFilter("/ajax/*")
public class AjaxFilter implements Filter {

   
        public AjaxFilter() {
       
        }

	
	public void destroy() {
		
	}

	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(!isAjaxRequest((HttpServletRequest)request)){
		   // The request doesn't comes through ajax
          // Take some action here
          // You can redirect to an error page, throw an exception, or just simply keep this block empty.
		}else 			
			chain.doFilter(request, response);
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		
	}
	
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
		return "xmlhttprequest".equals(request.getHeader("X-Requested-With").toLowerCase());
	}


}

Filter mapping

Now we need to specify for which controller’s we want to apply this filter. We can make this process simple if we keep “/ajax” in all the controller’s url mapping like: @WebServlet(“/ajax/myController”) or @WebServlet(“/ajax/anotherController”) etc. Then The following filter mapping will work for all ajax requests

  <filter>
  	<filter-name>AjaxFilter</filter-name>
  	<filter-class>net.hasnath.web.filters.AjaxFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>AjaxFilter</filter-name>
  	<url-pattern>/ajax/*</url-pattern>
  </filter-mapping>

Comments

  • Thanks, please not that this will not totally solve the issue. One can tamper sent data and manually set the httpHeader to what ever he wants

    AlirezaJune 7, 2014

Leave a Reply