The Problem:
I am configuring Spring Security filter chain and defining FilterRegistrationBean. I have added custom filters using http.addFilterBefore(...)
and created a Filter configuration with FilterRegistrationBean<>
methods. However, I don’t know where these FilterRegistrationBean filter beans appear in the servlet filter chain and how their order is determined compared to the filters in the security filter chain.
The Solutions:
Solution 1: Filter Chain and FilterRegistrationBean in Spring Security
The Spring Security filter chain and `FilterRegistrationBean` play distinct roles in securing web applications:
- Security Filter Chain: Configured using `http.addFilterBefore(…)`, this chain contains filters related to security operations, such as authentication and authorization.
- `FilterRegistrationBean`: A bean-based approach to register custom filters. These filters are managed by the servlet container and can be placed before or after the security filter chain.
When a request is processed, the security filter chain runs first, followed by the `FilterRegistrationBean` filters, if any. This allows for flexibility in filter ordering and enables the separation of security-related filters from general application filters.
Note: To avoid duplicate filter executions, it’s recommended to exclude security filters from bean registration and instead configure them through the security filter chain configuration.
Q&A
Where do the ‘FilterRegistrationBean<>’ filter beans get in the servlet filter chain?
They are registered as separate servlet container filters.
What is the order of ‘FilterRegistrationBean<>’ filters?
They are placed according to the order you specify.
Which is the best way to define security related filters?
Security filters should go in the security filter chain.