如何通过application.properties禁用Spring Security?

4

我正在尝试激活带有密码哈希加密的基本身份验证

@Configuration //gets picked up automatically by spring-boot
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(details).passwordEncoder(new BCryptPasswordEncoder());
    }
}

我希望验证仅在生产环境中有效。因此,我首先尝试总体上禁用它,使用以下方法:

security.basic.enabled=false

结果:应用程序仍然受到保护。我会看到用户名/密码屏幕。
但是如何禁用身份验证的需求呢?
3个回答

3

ConditionalOnProperty解决方案:

@Configuration
@ConditionalOnProperty("security.basic.enabled")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

}

2

要在不同的环境中执行不同的操作,您应该使用Spring Profiles

假设您只需要在生产环境中加载安全配置bean,则应将其标记为仅在启用特定配置文件时有条件地加载。

@Configuration //gets picked up automatically by spring-boot
@Profile("Production")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(details).passwordEncoder(new BCryptPasswordEncoder());
    }
}

配置特定于配置文件的内容存储在名为application-{profile}.propertiesbootstrap-{profile}.properties的属性文件中。

现在,由于安全配置bean标记为Production,因此只有在启用Production配置文件时才会加载它。

要启用配置文件,您必须设置以下属性。

#One or more profiles can be active simultaneously
spring.profiles.active=Production,Dev,Local

这个属性可以在常用的属性文件application.properties中进行编辑(与针对特定配置文件,如application-Production.properties条件加载不同的是,常用属性文件总是会被加载),或者可以按下面提供的方式作为环境变量提供。

On Windows
set SPRING_PROFILES_ACTIVE=Production
On Unix
export SPRING_PROFILES_ACTIVE=Production

可以使用Spring支持的其他许多方式来加载属性。要查看所有方法的列表,请转到此链接 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

最后,要禁用默认的Spring安全(Basic)自动配置,您可以使用以下属性。

security.basic.enabled=false
management.security.enabled=false #For actuator

在您希望禁用Spring Security自动配置的特定属性文件中,应按照上述格式进行设置。

如上所述,我已经尝试使用security.basic.enabled=false,这通常应该有效,但在使用WebSecurityConfigurerAdapter时却无效。 - membersound
这是因为WebSecurityConfigurerAdapter仍在创建一个bean,必须根据答案开头提到的条件进行加载。 - 11thdimension
我两次扩展了WebSecurityConfigurerAdapter并按上述方式工作。效果非常好。 - DOUBL3P

-1

要完全禁用Spring Security自动配置,请使用以下属性

spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接