在 Spring Boot 中禁用某个 Profile 的安全性
上次更新: 2020 年 5 月 2 日
1. 概述
在本教程中,我们将了解如何为给定的 Profile 禁用 Spring Security。
2. 配置
首先,让我们定义一个简单的允许所有请求的安全配置。
我们可以通过注册一个WebSecurityCustomizer bean 并忽略所有路径的请求来实现这一点
@Configuration
public class ApplicationNoSecurity {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(new AntPathRequestMatcher("/**"));
}
}
请记住,这不仅关闭了身份验证,还关闭了任何安全保护,例如 XSS。
3. 指定 Profile
现在我们只想为给定的 Profile 激活此配置。
假设我们有一个不想启用安全性的单元测试套件。如果此测试套件使用名为“test” 的 Profile 运行,我们可以使用@Profile注解我们的配置
@Configuration
@Profile("test")
public class ApplicationNoSecurity {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(new AntPathRequestMatcher("/**"));
}
}
因此,我们的测试环境将会不同,这可能不是我们想要的。或者,我们可以保持安全性开启,并使用Spring Security 的测试支持。
4. 结论
在本教程中,我们展示了如何为特定 Profile 禁用 Spring Security。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















