我使用Spring Security OAuth2设置了一个Spring Boot多模块(5个模块)应用程序。一切正常,但是随着应用程序的增长,我想将每个模块中的安全部分分开。主模块启用所有功能:
@SpringBootApplication
@EnableResourceServer
@EnableAuthorizationServer
@EnableWebSecurity(debug = true)
public class Application {
...
}
现在在每个模块中,我都定义了ResourceServerConfigurer
类型的bean
@Configuration
@Order(2)
public class Module1SecurityFilterChain extends ResourceServerConfigurerAdapter {
@Override
public void configure( HttpSecurity http ) throws Exception {
http.sessionManagement().sessionCreationPolicy( STATELESS );
http.antMatcher( "/module1/**")
.authorizeRequests()
.antMatchers( "/module1/resource").authenticated()
.antMatchers( "/module1/test" ).authenticated()
.anyRequest().access( "#oauth2.hasScope('webclient')" );
}
}
与module2相同:
@Configuration
@Order(1)
public class Module2SecurityFilterChain extends ResourceServerConfigurerAdapter {
@Override
public void configure( HttpSecurity http ) throws Exception {
http.sessionManagement().sessionCreationPolicy( STATELESS );
http.antMatcher( "/module2/**")
.authorizeRequests()
.antMatchers( "/module2/resource").authenticated()
.antMatchers( "/module2/test" ).authenticated()
.anyRequest().access( "#oauth2.hasScope('webclient')" );
}
}
依此类推...
问题是只有一个FilterChain被注册,一个@Order(2)
。我看了ResourceServerConfigurer
的{{3}},它说明了这一点:
...如果有多个配置相同的预操作,则最后一个获胜。配置器在应用之前按顺序排序
如何继续绕过此限制? 非常感谢。
编辑
执行此操作(扩展WebSecurityConfigurerAdapter
而不是ResourceServerConfigurerAdapter
):
@Configuration
@Order(1)
public class Module2SecurityFilterChain extends WebSecurityConfigurerAdapter {...}
似乎正在注册过滤器链,但是还有另一个问题,当我对用户进行身份验证(在/oauth/token
上获得令牌)时,我无法访问受该链保护的资源,我得到了403 Forbidden
。黑匣子如何工作?
答案 0 :(得分:1)
您可以使用requestMatchers().antMatchers(String...)
跨多个bean配置多个匹配器,如下所示:
@Configuration
public class Module2SecurityFilterChain extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/module2/**")
.authorizeRequests()
.antMatchers("/module2/resource").authenticated()
.antMatchers("/module2/test").authenticated()
.anyRequest().access("#oauth2.hasScope('webclient')");
}
}
这有点令人困惑,但是当您调用http.antMatcher(String)
时,这表明您只想与该端点匹配。因此,调用两次(在Module1SecurityFilterChain
中,然后在Module2SecurityFilterChain
中再次),第二个调用将覆盖第一个调用。
但是,使用http.requestMatchers().antMatchers(String)
表示应将给定的String
添加到已经匹配的端点的现有列表中。您可以将antMatcher
看作是“ setMatcher
”,将antMatchers
看作是“ appendMatcher
”。