通过Java配置禁用Spring Security?

mas*_*asa 5 java spring spring-security

我有一个Java应用程序,通过Java配置使用Spring Security.

在编译中打开/关闭整个Spring Security的最简单方法是什么?

因此,像这样的,但对于不使用XML的配置.

编辑:

应用@Profile后,我的代码如下:

@Configuration
@Profile("SecurityOn")
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
Run Code Online (Sandbox Code Playgroud)

问题是如果未激活配置文件"SecurityOn",Spring Security将使用某些默认配置.相反,在这种情况下如何完全关闭Spring Security?

Dre*_*rew 6

要禁用该行为,您可以添加另一个类如下所示:

@Configuration
@EnableWebMvcSecurity
@Profile("!SecurityOn")
public class WebSecurityConfigDisable extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/**").permitAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当您运行应用程序时,您需要登录的唯一时间是SecurityOn配置文件处于活动状态.如果您正在使用Maven和Spring Boot,则启用登录的命令如下.

mvn spring-boot:run -Dspring.profiles.active=SecurityOn
Run Code Online (Sandbox Code Playgroud)

在没有配置文件或其他配置文件的情况下运行它将禁用登录.这对本地开发很有用.

我发现这在使用时是必要的,spring-boot-starter-security因为有默认配置需要登录.


Bon*_*ond 0

考虑使用配置文件功能。

由于@Profile可以作为方法级注释应用于任何@Bean方法,因此您可以使用单个配置文件(例如“安全”)并仅注释相关@Bean方法。

然后通过 JVM 系统属性指定活动配置文件(作为环境变量),或者对于 Web 应用程序作为 Servlet 上下文参数web.xml

请参阅此处的示例用法。