0

I am playing around with spring boot + spring security and filter chain configuration and have noticed something for which I don't find much relevant information in the spring docs.

I have a security filter chain config, where I have added a couple of custom filters (using http.addFilterBefore(...))

I have also created a Filter configuration such that it defines several FilterRegistrationBean<> methods.

When booting the application, the logger prints the SecurityFilterChain, which contains the custom filters defined in the security filter chain config, however, I want to know where the rest of the filter beans exist in the servlet filter chain.

I inspected the filter chain architecture when using spring security and know that the DelegatingFilterProxy contains the FilterChainProxy which in turn contains all security filters, as defined by each SecurityFilterChain configuration.

Where do the FilterRegistrationBean<> filter beans get in the servlet filter chain? I like the flexibility they provide, but don't know how they are placed in order to properly order my filter chain.

  • You can find the ordering here: [Spring 4.2.1 Release](https://docs.spring.io/spring-security/site/docs/4.2.1.RELEASE/reference/htmlsingle/#filter-ordering) – k9yosh Jun 29 '23 at 10:19
  • but that only includes the Security Filter Chain ordering. What about the "other" filters i.e. those created as FilterRegistrationBean<>? – Dimitar Genov Jun 29 '23 at 10:22
  • 1
    Try this [answer](https://stackoverflow.com/a/26147788/2999358) – k9yosh Jun 29 '23 at 10:37

1 Answers1

1

Okay, I did some more debugging and troubleshooting and found out the answer:

Security filter chain comes after the requestContextFilter, as a separate servlet container filter. It holds all filters internal to it, while FilterRegistrationBean<> filters are registered as separate servlet container filters.

To answer my own question, registering filters as FilterRegistrationBean<> puts them in the servlet container filter chain according to the order you specify, meaning, you could place them before/after the security filter chain based on your requirement.

In my case and opinion, one should first think about the purpose of each filter:

  1. Filters that deal solely with security, e.g authentication should go in the security filter chain
  2. General application filters, e.g logging filter should be registered as FilterRegistration<> beans, which eventually get placed in the servlet filter chain

Note: Keep in mind that security filters should not be declared as beans, as that would put them as servlet container filters, which might result in the same filter being called twice in the filter chain.

  • You can declare security filters as beans if you set `filterRegistrationBean.setEnabled(false);` in the FilterRegistrationBean. That will prevent it from being added to the default filter chain. Then add the bean as a filter in the security filter chain. – mouse_8b Aug 31 '23 at 03:00