禁用Spring Boot中的Spring Security的方法

1,285 阅读2分钟

了解如何根据选定的运行时配置文件在Spring boot应用程序中部分或完全禁用Spring安全。我们可以使用这个例子来覆盖不同运行时配置文件中的安全配置。

1.禁用一个配置文件的Spring Security

要完全禁用运行时配置文件的Spring Security,我们可以在我们的应用程序中创建以下配置。该配置将忽略环境中所有类型的URL的安全配置。 *psdev*环境。

@Profile("psdev")
@Configuration
@Component("disableSecurityConfigurationBean")
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class DisableSecurityConfiguration extends WebSecurityConfigurerAdapter {

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

    //OR - Use any one of these two methods

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
        	.authorizeRequests()
        	.antMatchers("/")
        	.permitAll();
    }
}

注意*@Order(value = Ordered.HIGHEST_PRECEDENCE)*注解。我们给了它在psdev 环境中适用的最高优先级,所以如果有其他适用于所有环境的安全相关配置项,我们可以在psdev 环境中覆盖WebSecurity 的配置。

如果我们的应用程序中有多个WebSecurityConfigurerAdapter 实现,那么[@Order](https://howtodoinjava.com/spring-aop/spring-aop-specifying-aspects-ordering/) 注释就很有用。我们首先根据需求决定配置的顺序,并在@Order 注释中分配相应的优先级。

我们可以使用以下命令运行应用程序,以应用运行时配置文件。

mvn spring-boot:run -Dspring-boot.run.profiles=psdev

2.使用属性配置停用Spring Security

这也可以根据属性条目来启用、禁用或自定义Spring安全配置。在不同的运行时配置文件中,属性值可以设置得不同,因此每个配置文件可以对适用的安全配置进行更精细的控制。

在给定的例子中,我们有一个属性application.security.disabled ,可以有一个boolean 的值。根据它的值,我们可以应用不同的配置,甚至禁用配置。

@Configuration
@EnableWebSecurity
public class CustomSecurityConfiguration 
	extends WebSecurityConfigurerAdapter {

	@Value("${application.security.disabled:false}")
	private boolean securityDisabled;

	@Override
	public void configure(WebSecurity web) throws Exception {
	     
	   if (securityDisabled){ 
	      //config one
	    }
	    else{
	      //config two
	    }  
	}
}

我们可以在一个特定的配置文件中配置这个属性的键/值,也可以通过服务器启动参数来传递它。

mvn spring-boot:run -Dapplication.security.disabled=true

3.总结

在本教程中,我们学习了如何为spring boot应用程序启用或禁用spring security。我们学会了使用@Profile 注释或将属性作为启动参数传递来启用或禁用配置。

学习愉快!!