Search code examples
springspring-bootspring-security

Spring Security Filter Chain and defining FilterRegistartionBean


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.


Solution

  • 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.