How is the order of built-in filters maintained in Spring Security? I think many developers are interested in this question. In this article, I will discuss this issue with you.
HttpSecurity contains a member variable
FilterOrderRegistration and this class is a built-in filter registry. As for the role of these filters, not the focus of this article, interested to see the
FilterOrderRegistration source code.
Order of built-in filters
FilterOrderRegistration maintains a variable
filterToOrder that records the order between classes and the interval steps between the top and bottom. We copied a
FilterOrderRegistration to visualize the order of the filters.
We can see that the position between the built-in filters is relatively fixed, except for the first and second steps of
200 and the other steps of
The built-in filters do not always take effect, they are simply prepositioned and need to be added explicitly via the
addFilterXXXXseries of methods in
Logic for registering filters
FilterOrderRegistration provides a
From this approach we can draw several conclusions.
- The built-in
34filters have a fixed serial number and cannot be changed.
- The class-qualified name of a newly added filter cannot be duplicated with the built-in filter.
- The order of the newly added filters can be duplicated with the order of the built-in filters.
Get the order value of registered filters
FilterOrderRegistration also provides a
HttpSecurity methods for maintaining filters
Next we analyze a few of the methods that
HttpSecurity uses to maintain filters.
addFilterAtOffsetOf is a built-in private method of
Filter is the filter you want to register to the
offset is the offset to the right,
registeredFilter is the filter already registered to the
registeredFilter will throw a null pointer exception if it is not registered.
Always remember that
registeredFiltermust be a
Filterthat is registered in
addFilter series methods
Here is an example of
addFilterAfter is to place
filter one place after
afterFilter, if the order of
400, then the order of
addFilterAt logic and the
addFilterAfter logic are only differences in offset values, so we won’t go over them here.
addFilter method is special.
filter must be a
Filter that has been registered to
FilterOrderRegistration, which means it may be a built-in
Filter or it may be a non-built-in
Filter previously registered via
Here comes the problem
I saw a question earlier, if
HttpSecurity registers two
Filters with duplicate serial numbers, what will be the order? Let’s look at the ordering mechanism first.
After looking at the
OrderComparator source code, it is still sorted by the natural order of numbers, the smaller the number, the higher it is. If the numbers are the same, the smaller the index, the higher it is. That is to say, whoever
filters first is the first in the same order number.