Search code examples
javascalaplayframework

Play framework "play.filters.enabled" cannot work if "play.http.filters" is set


I am using play framework 2.8.16.

I defined Filters.scala in my application and enable it in application.conf

play.http.filters = com.xxx.xxx.Filters

I have another setting

play.filters.enabled += play.filters.https.RedirectHttpsFilter

RedirectHttpsFilter will be ignored.

Is it expected? How to support both?


Solution

  • It's expected and documented.

    Play comes with a default set of enabled filters, defined through configuration. If the property play.http.filters is null, then the default is now play.api.http.EnabledFilters, which loads up the filters defined by fully qualified class name in the play.filters.enabled configuration property.

    (...)

    You can also combine EnabledFilters with your own filters in code:

    Scala:

    class Filters @Inject() (enabledFilters: EnabledFilters, corsFilter: CORSFilter)
       extends DefaultHttpFilters(enabledFilters.filters :+ corsFilter: _*)
    

    Java:

    public class Filters extends DefaultHttpFilters {
    
      @Inject
      public Filters(EnabledFilters enabledFilters, CORSFilter corsFilter) {
        super(combine(enabledFilters.asJava().getFilters(), corsFilter.asJava()));
      }
    
      private static List<EssentialFilter> combine(
          List<EssentialFilter> filters, EssentialFilter toAppend) {
        List<EssentialFilter> combinedFilters = new ArrayList<>(filters);
        combinedFilters.add(toAppend);
        return combinedFilters;
      }
    }
    

    Otherwise, if you have a Filters class in the root or have play.http.filters defined explicitly, it will take precedence over the EnabledFilters functionality described below.

    If you change the value of play.http.filters configuration to your custom class, then all the logic to add/remove filters with play.filters.enabled is not applied anymore.

    Either:

    • stick to configuration file only filters with the default mechanism,
    • or inject EnabledFilters in your com.xxx.xxx.Filters to support both,
    • or load all filters from your com.xxx.xxx.Filters class (this would mean also the ones declared in default config files of Play, not recommended).