使用security我们最常见的代码:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}@Beanpublic PasswordEncoder getPasswordWncoder(){return new BCryptPasswordEncoder();}
}
这段代码源头是WebSecurityConfiguration这个类下的
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)public Filter springSecurityFilterChain() throws Exception {boolean hasConfigurers = webSecurityConfigurers != null&& !webSecurityConfigurers.isEmpty();if (!hasConfigurers) {WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {});webSecurity.apply(adapter);}return webSecurity.build();}
首先解释一下这部分代码的作用是返回内置过滤器和用户自己定义的过滤器集合,当然下一节讲解security是怎么使用拿到的过滤器。
setFilterChainProxySecurityConfigurer
webSecurity来自WebSecurityConfiguration中的
@Autowired(required = false)public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor<Object> objectPostProcessor,@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)throws Exception {webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));if (debugEnabled != null) {webSecurity.debug(debugEnabled);}Collections.sort(webSecurityConfigurers, AnnotationAwareOrderComparator.INSTANCE);Integer previousOrder = null;Object previousConfig = null;for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) {Integer order = AnnotationAwareOrderComparator.lookupOrder(config);if (previousOrder != null && previousOrder.equals(order)) {throw new IllegalStateException("@Order on WebSecurityConfigurers must be unique. Order of "+ order + " was already used on " + previousConfig + ", so it cannot be used on "+ config + " too.");}previousOrder = order;previousConfig = config;}for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {webSecurity.apply(webSecurityConfigurer);}this.webSecurityConfigurers = webSecurityConfigurers;}
setFilterChainProxySecurityConfigurer方法使用的是参数注入的方式,List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)参数会依赖查询SecurityConfigurer实例。
好的我们现在再回头看我们自己定义的SecurityConfig类是继承于WebSecurityConfigurerAdapter ,
可以看到WebSecurityConfigurerAdapter 实现WebSecurityConfigurer接口
WebSecurityConfigurer又继承SecurityConfigurer,T此时是WebSecurityConfigurer传递过来的WebSecurity,因此满足SecurityConfigurer<Filter, WebSecurity>,所以也会被setFilterChainProxySecurityConfigurer方法依赖查询到,下面我们debug一下
有人说这个不能保证就是我们定义类,那好我们给我们自己的类加个标识属性 securityName=“securityName”
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private String securityName="securityName";@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}
}
因此就是我们自己定义的类实例被成功依赖查询到作为参数。
好的我们现在接着回到WebSecurityConfiguration类的setFilterChainProxySecurityConfigurer方法
//创建webSecurity实例
webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));
for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {webSecurity.apply(webSecurityConfigurer);}
将所有SecurityConfigurer实例作为参数调用webSecurity的apply属性
public <C extends SecurityConfigurer<O, B>> C apply(C configurer) throws Exception {add(configurer);return configurer;}
继续看add方法
会将SecurityConfigurer添加到webSecurity的configurers属性中。以上过程都是在讲收集SecurityConfigurer并装配到webSecurity的configurers属性。下面继续将我们的源头函数springSecurityFilterChain是怎么使用webSecurity的
springSecurityFilterChain
public Filter springSecurityFilterChain() throws Exception {boolean hasConfigurers = webSecurityConfigurers != null&& !webSecurityConfigurers.isEmpty();if (!hasConfigurers) {WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {});webSecurity.apply(adapter);}return webSecurity.build();}
主要关心这行代码webSecurity.build()
public final O build() throws Exception {if (this.building.compareAndSet(false, true)) {this.object = doBuild();return this.object;}throw new AlreadyBuiltException("This object has already been built");}
继续看doBuild()
@Overrideprotected final O doBuild() throws Exception {synchronized (configurers) {buildState = BuildState.INITIALIZING;beforeInit();init();buildState = BuildState.CONFIGURING;beforeConfigure();configure();buildState = BuildState.BUILDING;O result = performBuild();buildState = BuildState.BUILT;return result;}}
doBuild分别调用了init(),configure(),performBuild()
init()
@SuppressWarnings("unchecked")private void init() throws Exception {Collection<SecurityConfigurer<O, B>> configurers = getConfigurers();for (SecurityConfigurer<O, B> configurer : configurers) {configurer.init((B) this);}for (SecurityConfigurer<O, B> configurer : configurersAddedInInitializing) {configurer.init((B) this);}}
这里调用了getConfigurers()方法
private Collection<SecurityConfigurer<O, B>> getConfigurers() {List<SecurityConfigurer<O, B>> result = new ArrayList<SecurityConfigurer<O, B>>();for (List<SecurityConfigurer<O, B>> configs : this.configurers.values()) {result.addAll(configs);}return result;}
this.configurers就是前面SecurityConfigurer存放的位置,这里做的就是将我们的SecurityConfigurer实例存入一个数组中。好到回到我们刚才的位置init()方法
private void init() throws Exception {Collection<SecurityConfigurer<O, B>> configurers = getConfigurers();for (SecurityConfigurer<O, B> configurer : configurers) {configurer.init((B) this);}for (SecurityConfigurer<O, B> configurer : configurersAddedInInitializing) {configurer.init((B) this);}}
可以清除的看到遍历所有的SecurityConfigurer实例并调用其init(WebSecurity webSecurity)方法。那我们现在看看,我们自己定义的SecurityConfigurer实例init(WebSecurity webSecurity)方法具体的是怎样执行的。
首先找到
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private String securityName="securityName";@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}
}
alt+鼠标左键点击configure(HttpSecurity http)快速定位
在getHttp()方法内,接着网上找alt+鼠标左键点击getHttp,
final HttpSecurity http = getHttp();web.addSecurityFilterChainBuilder(http)
原来是创建HttpSecurity实例并将对应的HttpSecurity 放入到webSecurity中,因此我们这里可以得出通过调用webSecurity的init()方法,将所有依赖查询到SecurityConfigurer实例的httpSecurity实例存放到webSecurity的securityFilterChainBuilders集合属性中。原来我们定义的
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}@Beanpublic PasswordEncoder getPasswordWncoder(){return new BCryptPasswordEncoder();}
}
这段代码就是这样被用起来的,但是还没结束。继续看webSecurity的configure方法。
configure
调用的都是SecurityConfigurer实例的configure(webSecurity)方法,这个方法具体做了什么呢?
我们只需要关心SecurityConfigurer的configure方法在这里可以拿到webSecurity。继续看performBuild()
performBuild
注意我们将的init(),configu(),performBuild都是webSecurity的成员方法,因此
先看一个简单的功能
debugEnabled控制了日志打印,debugEnabled又是webSecurity属性,我们又能在SecurityConfigurer的configure(webSecurity)方法拿到webSecurity,是不是我们就可以在configure(webSecurity)设置debugEnabled,好的我们尝试一下。
没有设置的效果
添加修改代码
@Overridepublic void configure(WebSecurity web) throws Exception {super.configure(web);web.debug(true);}
但是这个功能不是我们主要讲的。回到performBuild()方法,我们的重点代码部分
securityFilterChainBuilders不就是存所有SecurityConfigurer实例的htttpSecurity集合属性。
这里就是遍历所有的httpSecurity属性,调用其的build方法。此时调用的httpSecurity的build,因此我们找到httpSecurity的performBuild()
requestMatcher和filters是什么?记住这两个属性并带着疑问回到我们常见的代码
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private String securityName="securityName";@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}
}
原来filters就是我们定义的过滤器。接着探索requestMatcher是什么
我们先看 http.authorizeRequests()方法
接着看getOrApply()方法
继续看apply()
接着看add()
原来configurer是放入到了HttpSecurity的configurers中,是不是此时有点明白但又有点不明白,总结:我们自己定义的WebSecurityConfigurerAdapter放入到了webSecurity的configurers属性中,而在WebSecurityConfigurerAdapter调用http.formLogin(),http.authorizeRequests()创建的configurer放到各自WebSecurityConfigurerAdapter实例的httpSecurity实例的configurers中。
其实我们查看类也能看到WebSecurityConfigurerAdapter和http.formLogin(),http.authorizeRequests()产生的configurer都继承于SecurityConfigurer,而webSecurity和httpSecurity都继承于和实现相同的类和接口。
所以我们也可以得出httpSecurity调用configure方法其实是调用的http.formLogin(),http.authorizeRequests()产生的configurer实例的configurer(HttpSecurity)方法。
requestMatcher是什么呢
回到
查看antMatchers方法
查看RequestMatchers.antMatchers(antPatterns)的antMatchers方法
原来RequestMatchers.antMatchers(antPatterns)方法将我们的路径封装成了RequestMatcher集合,回到
查看chainRequestMatchers方法
这里我们要回到http.authorizeRequests()
查看getRegistry方法返回的是ExpressionInterceptUrlRegistry类型
ExpressionInterceptUrlRegistry该类继承于ExpressionUrlAuthorizationConfigurer.AbstractInterceptUrlRegistry
AbstractInterceptUrlRegistry继承AbstractConfigAttributeRequestMatcherRegistry
所以这里chainRequestMatchers是AbstractConfigAttributeRequestMatcherRegistry的方法
查看chainRequestMatchersInternal方法,chainRequestMatchersInternal此时是ExpressionUrlAuthorizationConfigurer的成员方法
因此返回的是 new AuthorizedUrl(requestMatchers);
回到
继续看AuthorizedUrl的permitAll()方法
查看access方法
查看interceptUrl方法
整个流程
1.创建WebSecurity
2.调用WebSecurity的configure方法,创建HttpSecurity
3.调用WebSecurity的performBuild方法
4.调用HttpSecurity的configure方法,回调consfigure的consfigure(HttpSecurity)方法添加各自的过滤器到HttpSecurity的filters
5.打包HttpSecurity过滤器返回并添加到WebSecurity的securityFilterChains属性
6.封装WebSecurity的securityFilterChains属性为FilterChainProxy
最终返回包含所有过滤器的 FilterChainProxy实例
下一节讲FilterChainProxy使用过程