我的代码中有多个WebSecurityConfigurerAdapter
,每个都在一个不同的类中。我们正在迁移到spring-security 5.2
,因此,我们应该删除@EnableResourceServer
,用oauth2RespourceServer
的DSL方式代替它。
第一个WebSecurityConfigurerAdapter
被称为CommonWebSecurityConfig
,它包括许多ant-matchers
,没有任何共享prefix:
@Configuration
@EnableWebSecurity
@ComponentScan
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CommonWebSecurityAutoConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
// .requestMatchers()
// .antMatchers("/* Should I add all (long) list of matchers here?*/")
// .and()
.authorizeRequests()
.antMatchers(GET, "/health").permitAll()
.antMatchers("/loggers/**").hasAuthority("scope1")
.antMatchers("/info/**").hasAuthority("scope2")
.antMatchers("/metrics/**").hasAuthority("scope3")
.antMatchers("/configurations/**").hasAuthority("scope4")
.antMatchers("/odata.svc/**").hasAuthority("scope5")
.antMatchers("/dataCenters/**").hasAuthority("scope6")
.antMatchers("/metadata/v1**").hasAuthority("scope7")
...
...
...
...
...
... // list goes on
...
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(getJwtAuthoritiesConverter());
}
第二个 WebSecurityConfigurerAdapter
是指 AccountsWebSecurityConfig
,它应该是第二个被验证的对象。也就是说,如果一个请求没有匹配到 CommonWebSecurityConfig
中的任何 ant matcher
,它应该被 AccountsWebSecurityConfig
验证。
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.xyz..**.security")
@Order(AFTER_COMMON)
public class AccountsWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
// .requestMatchers()
// .antMatchers("/accounts/**")
// .and()
.authorizeRequests()
.mvcMatchers("/accounts/v1/go").hasAuthority("scope33")
...
... // list goes on
...
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(getJwtAuthoritiesConverter());
}
我的问题
- 请求没有根据
AccountsWebSecurityConfig
进行验证:任何以 "accounts "开头的请求都被授予访问权! 当我取消了这两个类中configure()
开头的3行,它就开始工作了。这与我们在spring-security 5.2'之前的行为不同:我们不需要添加
requestMatchers’来使其工作。这是一个新的要求吗? - 如果是,那么我是否必须在所有的
antMatchers
中添加requestMatchers
?如果我有这么多不共享前缀的antMatchers
,如CommonWebSecurityConfig
,怎么办? - 我是否必须在这两个地方添加
and().oauth2ResourceServer()
?
StackOverflow:java - spring security 5.2 multiple WebSecurityConfigurerAdapter with oauth2ResourceServer - Stack Overflow