Spring Boot中的多个WebSecurityConfigurerAdapter无法一起工作



我有一个Spring Boot应用程序。它有两个WebSecurityConfigurerAdapter,其中一个在Spring库依赖项中(其他应用程序通用(:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.mycomp.common.security.**")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CommonWebSecurityConfig extends WebSecurityConfigurerAdapter {
http

.authorizeRequests()
.antMatchers("/configurations/**").hasAnyAuthority(TechnicalScope.ACTUATOR_ADMIN.getValue(), SystemScope.ACTUATOR_ADMIN.getValue())
.antMatchers(GET, "/jobs/scheduling/**").hasAuthority(TechnicalScope.JOB_READ.getValue())
.antMatchers(GET, "/odata.svc/**").hasAuthority(TechnicalScope.ODATA_READ.getValue())

}

第二个:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.mycomp.accounts.**.security")
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
http

.authorizeRequests()

.mvcMatchers(GET, "/swagger-ui.html").permitAll()
.mvcMatchers(GET, "/webjars/springfox-swagger-ui/**").permitAll()
.mvcMatchers(GET, "/swagger-resources/**").permitAll()
.mvcMatchers(GET, "/v2/api-docs/**").permitAll()
.mvcMatchers(GET, AccountController.BASE_PATH).hasAuthority(Scope.ACCOUNT_READ.getValue())
.mvcMatchers(PATCH, AccountController.BASE_PATH).hasAuthority(Scope.ACCOUNT_UPDATE.getValue())
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(getJwtAuthoritiesConverter());

}

问题:根据第一个WebSecurityConfigurerAdapterONLY的匹配器验证请求。忽略第二个匹配项。尝试调试时,我可以看到FilterSecurityInterceptor.obtainSecurityMetadataSource只使用第一个Configurer匹配器来维护requestMap

注意

  1. 当将第一个Configurer的所有匹配器移到第二个Configurer时,一切都如预期
  2. 两个配置程序在启动过程中都会被扫描

知道为什么FilterSecurityInterceptor中只考虑第一个配置程序吗?

我认为您在CommonWebSecurityConfig中错过了对requestMatchers的调用。

尝试这样做:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.mycomp.common.security.**")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CommonWebSecurityConfig extends WebSecurityConfigurerAdapter {
http.requestMatchers()
.antMatchers("/configurations/**").hasAnyAuthority(TechnicalScope.ACTUATOR_ADMIN.getValue(), SystemScope.ACTUATOR_ADMIN.getValue())
.antMatchers(GET, "/jobs/scheduling/**").hasAuthority(TechnicalScope.JOB_READ.getValue())
.antMatchers(GET, "/odata.svc/**").hasAuthority(TechnicalScope.ODATA_READ.getValue())
.authorizeRequests();
}

这是requestMatchers:的java文档

允许指定此HttpSecurity的哪个HttpServlet请求实例将在上调用。此方法允许轻松地调用多个不同RequestMatcher实例的HttpSecurity。要是…就好了单个RequestMatcher是必要的,请考虑使用mvcMatcher(String(、antMatcher(字符串(、regexMatcher(字符串requestMatcher(requestMatcher(。调用requestMatchers((将不会覆盖mvcMatcher(String(}的先前调用,requestMatchers((、antMatcher(String(、regexMatcher(字符串(和requestMatcher(requestMatcher(。

最新更新