Disable Security for a Profile in Spring Boot – 在Spring Boot中禁用一个配置文件的安全性

最后修改: 2020年 5月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’re going to take a look at how we can disable Spring Security for a given profile.

在本教程中,我们将看看如何为某个配置文件禁用Spring Security

2. Configuration

2.配置

First of all, let’s define a security configuration that simply allows all requests.

首先,让我们定义一个安全配置,简单地允许所有请求。

We can achieve this by registering a WebSecurityCustomizer bean and ignoring requests for all paths:

我们可以通过注册一个WebSecurityCustomizer bean并忽略所有路径的请求来实现这一目标。

@Configuration
public class ApplicationNoSecurity {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
            .antMatchers("/**");
    }
}

Remember that this shuts off not only authentication but also any security protections like XSS.

请记住,这不仅关闭了认证,也关闭了任何安全保护,如XSS.

3. Specify Profile

3.指定配置文件

Now we want to activate this configuration only for a given profile.

现在我们想只为一个特定的配置文件激活这个配置。

Let’s assume we have a unit test suite where we don’t want security. If this test suite runs with a profile named “test”, we can simply annotate our configuration with @Profile:

让我们假设我们有一个单元测试套件,我们不想要安全。如果这个测试套件以名为 “test “的profile运行,我们可以简单地@Profile来注释我们的配置。

@Configuration
@Profile("test")
public class ApplicationNoSecurity {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
            .antMatchers("/**");
    }
}

Consequently, our test environment will differ, which we may not want. Alternatively, we can leave security on and use Spring Security’s test support.

因此,我们的测试环境将有所不同,这可能是我们不希望看到的。另外,我们可以不开启安全功能并使用Spring Security的测试支持

4. Conclusion

4.总结

In this tutorial, we illustrated how to disable Spring Security for a specific profile.

在本教程中,我们说明了如何为一个特定的配置文件禁用Spring Security。

As always, the complete source code is available over on GitHub.

一如既往,完整的源代码可在GitHub上获得