两个configure方法在哪被调用
我们在编写Spring Security时配置类时,继承WebSecurityConfigurerAdapter,重写下面两个方法。
重写的两个方法在哪被调用了?
我觉得init(final WebSecurity web)一定会被调用,我没有深入。
以init方法调用下去,最终调用到了下面两个重写的方法。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
......
}
@Override
protected void configure(HttpSecurity http) throws Exception {
......
}
1.init方法中调用getHttp
2.getHttp调用authenticationManager
3.authenticationManager调用configure(AuthenticationManagerBuilder auth)
4.回到getHttp
5.调用configure(HttpSecurity http)
public void init(final WebSecurity web) throws Exception {
final HttpSecurity http = getHttp();
.....
}
protected final HttpSecurity getHttp() throws Exception {
if (http != null) {
return http;
}
AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);
//调用authenticationManager()
AuthenticationManager authenticationManager = authenticationManager();
authenticationBuilder.parentAuthenticationManager(authenticationManager);
Map<Class<?>, Object> sharedObjects = createSharedObjects();
http = new HttpSecurity(objectPostProcessor, authenticationBuilder,
sharedObjects);
if (!disableDefaults) {
// @formatter:off
http
.csrf().and()
.addFilter(new WebAsyncManagerIntegrationFilter())
.exceptionHandling().and()
.headers().and()
.sessionManagement().and()
.securityContext().and()
.requestCache().and()
.anonymous().and()
.servletApi().and()
.apply(new DefaultLoginPageConfigurer<>()).and()
.logout();
// @formatter:on
ClassLoader classLoader = this.context.getClassLoader();
List<AbstractHttpConfigurer> defaultHttpConfigurers =
SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
http.apply(configurer);
}
}
//调用configure(HttpSecurity http)
configure(http);
return http;
}
protected AuthenticationManager authenticationManager() throws Exception {
......
//调用configure(AuthenticationManagerBuilder auth)
configure(localConfigureAuthenticationBldr);
......
}
两个userDetailsService方法
HttpSecurity.userDetailsService方法AuthenticationManagerBuilder.userDetailsService方法
这两个方法效果一样,修改的是同一个AuthenticationManagerBuilder对象,该对象存放在HttpSecurity(HttpSecurity基础了AbstractConfiguredSecurityBuilder)对象的sharedObjects属性中。
sharedObjects是AbstractConfiguredSecurityBuilder的属性,是Map<Class<?>, Object>类型。
我认为他的作用是存放那些不确定是否需要的类的对象,这样更灵活
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.userDetailsService(userDetailsService);
}