Spring Boot 2.0.x禁用某些配置文件的安全性

leo*_*onz 10 java spring-security spring-boot

在Spring Boot 1.5.x中,我已经配置了安全性,并且在某些配置文件中(例如本地),我已经security.basic.enabled=false在.properties文件中添加了一行来禁用该配置文件的所有安全性.我正在尝试迁移到新的Spring Boot 2,其中删除了该配置属性.如何在Spring Boot 2.0.x中实现相同的行为(不使用此属性)?

我已经阅读过Spring-Boot-Security-2.0security-change-in-spring-boot-2-0-m4,这个属性没什么.

dur*_*dur 13

您必须添加自定义Spring Security配置,请参阅Spring Boot Reference Guide:

28.1 MVC安全性

默认安全配置在SecurityAutoConfiguration和中实现UserDetailsServiceAutoConfiguration.SecurityAutoConfiguration导入SpringBootWebSecurityConfigurationWeb安全性并UserDetailsServiceAutoConfiguration配置身份验证,这也与非Web应用程序相关.要完全关闭默认Web应用程序安全配置,您可以添加类型的bean WebSecurityConfigurerAdapter(这样做不会禁用UserDetailsService配置或Actuator的安全性).

例如:

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
           .ignoring()
               .antMatchers("/**");
    }
}
Run Code Online (Sandbox Code Playgroud)

仅将配置用于配置文件添加@Profile到类.如果要按属性启用它,请添加ConditionalOnProperty到类中.

  • 请注意,如果您有多个不相互排斥的安全配置,您还应该定义 `@Order`。例如,如果您的主要安全配置使用默认配置文件(没有指定 `@Profile`)并且您将开发配置文件添加到另一个配置,那么当您在开发配置文件处于活动状态的情况下运行时,Spring 将不得不决定哪个配置优先. (2认同)

leo*_*onz 5

这就是我最终解决问题的方式。这是我的安全配置在Spring Boot 1.5.x中的外观示例。财产的安全性已被禁用security.basic.enabled=false

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/upload/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}
Run Code Online (Sandbox Code Playgroud)

由于security.basic.enabled在Spring Boot 2中已被删除(但仍保留为属性名),我最终将其security.enabled用作自定义属性。这是我的配置在Spring Boot 2中的外观示例:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${security.enabled:true}")
    private boolean securityEnabled;

    @Override
    public void configure(WebSecurity web) throws Exception {
        if (securityEnabled)
            web.ignoring().antMatchers("/upload/**");
        else
            web.ignoring().antMatchers("/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if (securityEnabled)
            http.csrf().disable().authorizeRequests()
                    .anyRequest().authenticated()
                    .and().httpBasic();
    }
}
Run Code Online (Sandbox Code Playgroud)


Abh*_*jee 5

还有另一个选项可以在 spring boot 2 中禁用安全性

@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
Run Code Online (Sandbox Code Playgroud)

在主类上添加这个