filter filters

Is it possible to add a RequestFilter

Question

Is it possible to add a RequestFilter? For instance, to check permissions on resources (like files).

Answer

Yes, beginning from version 7.3.3.0 it is possible to have a RequestFilter inside a module (in previous version the RequestFilter must be added manually in the web.xml (and in common classpath)).

From version 7.3.3.0 it is possible to define the RequestFilter in a module in spring like:


    <bean name="checkResourcePermissionFilter" class="org.jahia.bin.filters.ServletFilter">
        <property name="filter">
            <bean class="org.jahia.modules.checkresourcepermission.filter.CheckResourcePermissionFilter"/>
        </property>
        <property name="order" value="1.9"/>
  <property name="urlPatterns">
            <set>
                <value>*.html</value>
            </set>
        </property>
        <property name="dispatcherTypes">
            <set>
                <value>REQUEST</value>
                <value>ERROR</value>
                <value>FORWARD</value>
            </set>
        </property>
    </bean>  

You have to specify a name and the class must be a ServletFilter. The implementation of the RequestFilter (in example the CheckResourcePermissionFilter.java) must implement the javax.servlet.Filter:

 public class CheckResourcePermissionFilter implements javax.servlet.Filter { 

So, you have to implement the "doFilter" method like:

  @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
   throws IOException, ServletException {
  final HttpServletRequest hsRequest = (HttpServletRequest) request;
  HttpServletResponse hsResponse = (HttpServletResponse) response;  
  
        if (JahiaUserManagerService.isGuest(JCRSessionFactory.getInstance().getCurrentUser())) {
           //check Permission for guest user
            
            //TODO your custom filter code in case of error throw a 403 error
                if (.... ERROR ....) {
       hsRequest.getSession().setAttribute("resourceUri", hsRequest.getRequestURI());
       hsResponse.sendError(403);
       return;
                }
            }
        }
 // continue with filters
 chain.doFilter(request, response);
 } 

This codefragment is just an example and must be replaced by custom code.

 

NOTE: An error 401 will forward directly to a login screen (before Jahia 8, to the basic authentication), that's why it is recommended to send a 403 error. This will display the default 403 error page, which can be overwritten.