SpringSecurity基於Filter技術,經過一系列內置的或自定義的安全Filter,實現接口的認證與受權。咱們必定在使用的過程當中,定義過WebSecurityConfigurerAdapter的擴展,爲程序自定義配置邏輯。java
好比,咱們想要自定義基於JWT攔截的過濾器,咱們能夠經過addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
的方式,將過濾器按照必定順序加入過濾器鏈。spring
addFilterBefore在HttpSecurity類中:數組
public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) { comparator.registerBefore(filter.getClass(), beforeFilter); return addFilter(filter); }
見名知義,意思是在指定的beforeFilter以前加入filter。這裏的comparator是內置的一個用於比較註冊順序的一個類,能夠大體看一看:能夠看到構造器初始化了map,key爲過濾器的類對象,value爲order。安全
order的順序也是肯定的,舉個例子,ChannelProcessingFilter的order值爲100,後面每多一個,就加上100。ui
final class FilterComparator implements Comparator<Filter>, Serializable { private static final int INITIAL_ORDER = 100; private static final int ORDER_STEP = 100; private final Map<String, Integer> filterToOrder = new HashMap<>(); FilterComparator() { //初始化了一些默認的Filter並規定的order Step order = new Step(INITIAL_ORDER, ORDER_STEP);//越往下order越大 put(ChannelProcessingFilter.class, order.next()); //100 put(ConcurrentSessionFilter.class, order.next()); //200 put(WebAsyncManagerIntegrationFilter.class, order.next()); put(SecurityContextPersistenceFilter.class, order.next()); put(HeaderWriterFilter.class, order.next()); put(CorsFilter.class, order.next()); put(CsrfFilter.class, order.next()); put(LogoutFilter.class, order.next()); //...省略 }
compare方法定義了比較的規則:依照order排序,小的在前,大的在後。this
public int compare(Filter lhs, Filter rhs) { Integer left = getOrder(lhs.getClass()); Integer right = getOrder(rhs.getClass()); return left - right; }
以registerBefore
爲例,其餘相似的還有registerAt,registerAfter
。code
public void registerBefore(Class<? extends Filter> filter, Class<? extends Filter> beforeFilter) { Integer position = getOrder(beforeFilter);//獲得要加入的filter的位置 if (position == null) {} put(filter, position - 1);//將當的filter存入map }
向List<Filter>
中加入filter。orm
public HttpSecurity addFilter(Filter filter) { Class<? extends Filter> filterClass = filter.getClass(); if (!comparator.isRegistered(filterClass)) {} this.filters.add(filter);//向List<Filter> 中加入filter return this; }
在全部的Filter添加完成以後,Filter其實並無按照order進行排序,由於暫時仍是按照讀取的順序進行加入的List,只有當執行了HttpSecurity.performBuild
以後,才造成按照order排序的Filter數組。jwt
在進行sort以後,根據order進行排序,生成的列表List就是最終的Filter列表。對象