filterplayframework-2.5

Play Framework 2.5.12 - set multiple filter in application.conf


I'm using Play Framework 2.5.12 (Java version). When I declare a filter (Filters1) and set below config in application.conf:

 play.http.filters = my.filter.path.Filters1

It works fine.

But I have two filters:

  1. Filters1 extends DefaultHttpFilters class
  2. Filters2 extends Filter class

In Play Framework 2.6 , solution is:

play.http.filters += my.filter.path.Filters1
play.http.filters += my.filter.path.Filters2

I have tried that, but it didn't work in Play Framework 2.5. What is your solution?


Solution

  • Finally I couldn't handle this problem in application.conf.
    Solution :
    You have to pass your filter as a parameter in constructor of Filters1 and set it as EssentialFilters.
    This is my Filters1 class :

    import com.rh.ot.web.core.filters.CustomFilter;
    import play.Environment;
    import play.filters.gzip.GzipFilter;
    import play.filters.headers.SecurityHeadersFilter;
    import play.http.DefaultHttpFilters;
    import play.mvc.EssentialFilter;
    import javax.inject.Inject;
    import javax.inject.Singleton;
    
    @Singleton
    public class Filters1 extends DefaultHttpFilters {
    
        private final Environment env;
        private EssentialFilter[] filters;
    
        @Inject
        public Filters(Environment env, GzipFilter gzipFilter, SecurityHeadersFilter securityHeadersFilter, Filters2 filters2) {
            super(securityHeadersFilter);
            this.env = env;
            filters = new EssentialFilter[]{gzipFilter.asJava(), filters2.asJava()};
        }
    
        public EssentialFilter[] filters() {
            return filters;
        }
    }
    

    and Filters2 class :

    import akka.util.ByteString;
    import play.libs.streams.Accumulator;
    import play.mvc.EssentialAction;
    import play.mvc.EssentialFilter;
    import play.mvc.Result;
    import javax.inject.Inject;
    import java.util.concurrent.Executor;
    
    public class Filters2 extends EssentialFilter {
    
        private final Executor executor;
    
        @Inject
        public Filters2(Executor executor) {
            super();
            this.executor = executor;
        }
    
        @Override
        public EssentialAction apply(EssentialAction next) {
            return EssentialAction.of(request -> {
                request.headers().put("Strict-Transport-Security", new String[]{"max-age=31536000; includeSubDomains"});
                Accumulator<ByteString, Result> accumulator = next.apply(request);
                return accumulator.map(result -> result, executor);
            });
        }
    }