禁用 EnableGlobalMethodSecurity 注释

ram*_*lla 4 java spring spring-security

有没有办法可以使用我的 config.properties 中的 boolean securityEnabled 禁用全局方法安全性?还有其他方法吗?

@EnableWebSecurity 
@EnableGlobalMethodSecurity(securedEnabled=true) 
@PropertySource("classpath:config.properties")  
public class SecurityConfig 
  extends WebSecurityConfigurerAdapter {    

  @Value("${securityconfig.enabled}") 
  private boolean securityEnabled;

  ...

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*nch 8

最简单的方法是:

  • 将方法安全性提取到它自己的类
  • 完全删除 secureEnabled 属性
  • 覆盖 customMethodSecurityMetadataSource 方法并根据配置的值返回结果。

例如:

@EnableWebSecurity
@Configuration
@PropertySource("classpath:config.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
}

@EnableGlobalMethodSecurity
@Configuration
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Value("${securityconfig.enabled}")
    private boolean securityEnabled;

    protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
        return securityEnabled ? new SecuredAnnotationSecurityMetadataSource() : null;
    }    
}
Run Code Online (Sandbox Code Playgroud)

  • @RobWinch 这不适用于最新的 SpringBoot 版本。 (2认同)

PCa*_*che 5

我通过定义一个 Spring“securityDisabled”配置文件并有条件地应用基于它的安全配置来管理这个。我正在使用 Spring Boot 2.0.2。我相信如果不使用 Spring Boot 和以前版本的 Spring Boot,这应该可以工作,但我还没有测试过。可能需要对属性和类名进行一些调整,因为我知道在 Spring 2.0 中有些改变了。

// In application.properties
spring.profiles.include=securityDisabled
Run Code Online (Sandbox Code Playgroud)

然后我的安全配置如下所示:

@Configuration
public class SecurityConfig {

  // When the securityDisabled profile is applied the following configuration gets used
  @Profile("securityDisabled")
  @EnableWebSecurity
  public class SecurityDisabledConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Configure http as needed from Spring Security defaults when
        // NO security is desired
    }
  }

  // When the securityDisabled profile is NOT applied the following configuration gets used
  @Profile("!securityDisabled")
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  @EnableWebSecurity
  public class SecurityEnabledConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Configure http as needed from Spring Security defaults when
        // security is desired
    }
  }
}
Run Code Online (Sandbox Code Playgroud)