允许客户端应用程序从已连接的WebSecurityConfigurerAdapter配置http安全性

时间:2015-11-09 04:48:09

标签: spring spring-boot

我正在使用spring-boot和spring-security。

我为许多不同的项目设置了通用WebSecurityConfigurerAdapter。问题是我想为每个项目提供自定义Controller安全性,其他一切都保持不变。最明显的解决方案是使其成为抽象并强制每个项目扩展它,但我怀疑有更好的方法通过事件或其他东西。

以下是WebSecurityConfigurerAdapter

的配置方法
@Override
protected void configure(final HttpSecurity http) throws Exception {

    ...

    http.authorizeRequests()
    .antMatchers("/health*").permitAll()
    .antMatchers("/endpoints/**").permitAll()
    .antMatchers("/rest/open/**").permitAll()
    .antMatchers("/login/impersonate*").hasAnyRole("ADMIN", "ADMINISTRATOR")

    // AT THIS POINT I WOULD LIKE EACH PROJECT TO OPTIONALLY CONFIGURE http AS THEY WISH

    http.authorizeRequests().antMatchers("/**").authenticated();

    ...

}

有没有一种很酷的方法可以在春季通过bean配置或其他方式来做到这一点?

@Bean //something like this perhaps????
public void configureSecurity(final HttpSecurity http) {
   http.authorizeRequests()
     .antMatchers("/rest/admin*").hasAnyRole("ADMIN", "ADMINISTRATOR")
}

1 个答案:

答案 0 :(得分:1)

你可以使用多个WebSecurityConfigurerAdapter类,juste确保每个类都在Springboot自动配置扫描的包中。

如果客户端项目想要覆盖现有的安全性约束,请添加@Order注释:

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ClientSecurityConfig extends WebSecurityConfigurerAdapter {
      public void configure(HttpSecurity http) {
            http.antMatcher("/rest/admin*").authorizeRequests().anyRequest().hasAnyRole("ADMIN", "ADMINISTRATOR");
      }
}

注意authorizeRequests()之前的antMatcher(),这样做是为了限制客户端配置的范围。没有它,它将擦除所有默认配置(除了/ rest / admin *之外的每个URL将返回403 Unauthorized)。