我基于Spring 2.6的旧安全配置代码运行良好:
@Configuration @EnableWebSecurity
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
. . .
.and()
.oauth2ResourceServer()
.jwt();
}
}现在,我正在升级被废弃的WebSecurityConfigurerAdapter类的用法,转而使用@Bean来返回SecurityFilterChain 按建议,并且我的应用程序不再具有有效的AuthenticationEventPublisher:
@Configuration @EnableWebSecurity
public class ResourceServerConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
. . .
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
}
}造成我的问题的原因是:对象BearerTokenAuthenticationFilter使用ProviderManager作为AuthenticationManager (甚至在使用WebSecurityConfigurerAdapter之前)。但是,当默认的ProviderManager以这种方式声明其AuthenticationEventPublisher时:
public class ProviderManager implements AuthenticationManager, . . . {
. . .
private AuthenticationEventPublisher eventPublisher = new NullEventPublisher();--这就是问题所在: NullEventPublisher是一个不发布事件的空实现。
在使用WebSecurityConfigurerAdapter之前,ProviderManager的eventPublisher对象被指定为DefaultAuthenticationEventPublisher对象。
经过一些测试,我能够用以下代码“修复问题”:
@Configuration
@ConditionalOnClass({AuthenticationEventPublisher.class, JwtAuthenticationProvider.class})
public class SpringConfiguration { //global configuration for several others
@Bean
public ProviderManager providerManagerAvecDefaultAuthenticationPublisher(@Lazy JwtDecoder jwtDecoder, AuthenticationEventPublisher authenticationPublisher) {
JwtAuthenticationProvider authenticationProvider = new JwtAuthenticationProvider(jwtDecoder);
ProviderManager providerManager = new ProviderManager(Arrays.asList(authenticationProvider));
providerManager.setAuthenticationEventPublisher(authenticationPublisher);
return providerManager;
}
}还调整了我的安全配置:
@Configuration @EnableWebSecurity
public class ResourceServerConfig {
@Autowired ProviderManager manager; //1
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
. . .
.and()
.oauth2ResourceServer()
.jwt()
.authenticationManager(manager); //2
return http.build();
}
}但我有两个顾虑:
ProviderManager的风险。最后,我的问题是:是否有一种方法可以绕过eventPublisher = new NullEventPublisher()与ProviderManager的关系,而无需在所有配置SecurityFilterChain的应用程序中配置oauth2ResourceServer().authenticationManager(manager)?
发布于 2022-06-28 08:57:19
您对默认AuthenticationEventPublisher的假设似乎不正确。
实际上,默认的一个(DefaultAuthenticationEventPublisher)是通过:org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration#authenticationEventPublisher()提供的。
然后由AuthenticationConfiguration获取,它创建一个AuthenticationManagerBuilder,该AuthenticationManagerBuilder根据请求使用填充的事件发布者创建所述的ProviderManager。
https://stackoverflow.com/questions/72779864
复制相似问题