Search code examples
springspring-bootnetflix-zuul

Prevent Filter chain from execution based on condition


In my spring boot application I have the following filter registry:

@Bean
public FilterRegistry filterRegistry(Service1 service1, Service2 service2,
            EvictionService evictionService) throws GeneralSecurityException {
      FilterRegistry r = FilterRegistry.instance();

      r.put("filter1", new MetadataFilter(Service2,evictionService));
      r.put("filter2", new RoutesFilter(service1,evictionService, publicKey));

      return r;
}

In the first filter I need to check on a condition, if this condition is true I want to skip all filters in my filter registry. What I am having now is that I do the check in the beginning of each filter like this:

public class Filter1 extends ZuulFilter {
    public boolean shouldFilter() {
            if(condition){
            return false;
            }
            return true
    }

}

public class Filter2 extends ZuulFilter {
    public boolean shouldFilter() {
            if(condition){
            return false;
            }
            return true
    }

}

but What I really want is to create a new filter that holds the condition, run the condition filter at the beginning and if condition is true then do not continue in the filter registry execution.

any ideas?


Solution

  • This can be achieved logically by adding a request attribute in your decision filter.

    The Decision Making Filter should look like following.

    public class DecisionFilter extends ZuulFilter {
    
        // .... Other methods and codes
    
        @Override
        public Object run() {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
    
            if(shouldExecuteFilter1()) {
                request.setAttribute("executeFilter1", true);
            } 
    
            if (shouldExecuteFilter2()) {
                request.setAttribute("executeFilter2", true);
            }
        }
    }
    

    Now, the Operational Filters will just fetch the corresponding attribute from request and execute the operation if true.

    public class FilterOne extends ZuulFilter {
        @Override
        public Object run() {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
    
            if (servletRequest.getAttribute("executeFilter1") != null || ((Boolean) servletRequest.getAttribute("executeFilter1"))) {
                // Perform your task
            }
        }
    }
    

    Similarly you can implement any number of filters with one decision making filter which runs first.