Spring Boot 2.0.x禁用某些配置文件的安全性
在Spring Boot 1.5.x中,我已经配置了安全性,并且在某些配置文件中(例如本地),我已将security.basic.enabled=false
行添加到.properties文件中以禁用该配置文件的所有安全性。 我正在尝试迁移到新的Spring Boot 2,其中删除了该配置属性。 如何在Spring Boot 2.0.x中实现相同的行为(不使用此属性)?
我已经阅读过Spring-Boot-Security-2.0和security-change-in-spring-boot-2-0-m4 ,这个属性没什么。
您必须添加自定义Spring Security配置,请参阅Spring Boot Reference Guide :
28.1 MVC安全性
默认安全配置在
SecurityAutoConfiguration
和UserDetailsServiceAutoConfiguration
。SecurityAutoConfiguration
导入用于Web安全的SpringBootWebSecurityConfiguration
和UserDetailsServiceAutoConfiguration
配置身份validation,这也适用于非Web应用程序。 要完全关闭默认Web应用程序安全性配置,可以添加WebSecurityConfigurerAdapter
类型的bean(这样做不会禁用UserDetailsService
配置或Actuator的安全性)。
例如:
@Configuration public class ApplicationSecurity extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/**"); } }
要仅为配置文件使用配置,请将@Profile
添加到类中。 如果要按属性启用它,请将ConditionalOnProperty
添加到类中。
以下是我最终解决问题的方法。 以下是我的安全配置在Spring Boot 1.5.x中的外观示例。 使用属性security.basic.enabled=false
禁用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(); } }
由于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(); } }
实际上这个问题的某些配置有几个答案; 在我的情况下,我一直在使用Spring Security和JWT玩Spring Boot 2。 为了保护我的REST端点,我需要创建令牌等。在我编写代码并尝试测试我的端点以查看JWT是否正常工作之后,我最终面临默认登录页面。 我尝试更改上面提到的属性文件,最后通过将@SpringBootApplication(exclude = {SecurityAutoConfiguration.class} )
注释添加到我的应用程序类来禁用它。
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class} ) public class JwtWithSpringBootApplication { public static void main(String[] args) { SpringApplication.run(JwtWithSpringBootApplication.class, args); } }