Spring Boot Security 自动配置
最后更新:2024年2月29日
1. 概述
在本教程中,我们将了解 Spring Boot 对安全性的约定方法。
简单来说,我们将重点关注默认安全配置,以及如何在需要时禁用或自定义它。
更多阅读
Spring Security - permitAll() 和 web.ignoring()
Spring Security 中 access="permitAll",filters="none",security="none" 的区别。
了解更多 →
2. 默认安全设置
为了向 Spring Boot 应用程序添加安全性,我们需要添加 security starter 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
这也会包含包含初始/默认安全配置的 SecurityAutoConfiguration 类。
请注意,我们在这里没有指定版本,假设项目已经将 Boot 用作父项目。
默认情况下,身份验证已为应用程序启用。 并且使用内容协商来确定是使用 basic 还是 formLogin。
有一些预定义的属性
spring.security.user.name
spring.security.user.password
如果我们不使用预定义的属性 spring.security.user.password 配置密码并启动应用程序,则会随机生成默认密码并打印在控制台日志中
Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6
有关更多默认值,请参阅 Spring Boot Common Application Properties 参考页面的安全属性部分。
3. 禁用自动配置
为了丢弃安全自动配置并添加我们自己的配置,我们需要排除 SecurityAutoConfiguration 类。
我们可以通过简单的排除来完成
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class SpringBootSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}
或者,我们可以将一些配置添加到 application.properties 文件中
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
但是,也存在一些特定的情况,在这种情况下,此设置还不够。
例如,几乎每个 Spring Boot 应用程序都以 Actuator 在类路径中启动。 这会导致问题,因为另一个自动配置类需要我们刚刚排除的那个。 因此,应用程序将无法启动。
为了解决此问题,我们需要排除该类;并且,具体到 Actuator 的情况,我们还需要排除 ManagementWebSecurityAutoConfiguration。
3.1. 禁用 vs 取代安全自动配置
禁用自动配置和取代它之间存在显著差异。
禁用它就像添加 Spring Security 依赖以及从头开始的整个设置一样。 这在几种情况下可能很有用
- 将应用程序安全性与自定义安全提供程序集成
- 将已存在安全设置的传统 Spring 应用程序迁移到 Spring Boot
但大多数时候我们不需要完全禁用安全自动配置。
这是因为 Spring Boot 配置为允许通过添加我们新的/自定义配置类来取代自动配置的安全。 这通常更容易,因为我们只是自定义现有的安全设置来满足我们的需求。
4. 配置 Spring Boot 安全
如果我们选择了禁用安全自动配置的路径,那么自然需要提供我们自己的配置。
如前所述,这是默认安全配置。 然后我们通过修改属性文件来自定义它。
例如,我们可以通过添加我们自己的密码来覆盖默认密码
spring.security.user.password=password
如果我们想要更灵活的配置,例如多个用户和角色,我们需要使用一个完整的@Configuration类
@Configuration
@EnableWebSecurity
public class BasicConfiguration {
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder.encode("admin"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(request -> request.anyRequest()
.authenticated())
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
return encoder;
}
}
如果禁用默认的安全配置,@EnableWebSecurity 注解至关重要。
如果缺少它,应用程序将无法启动。
另外,请注意,在使用 Spring Boot 2 时,使用PasswordEncoder 设置密码是必需的。 更多详细信息,请参阅我们的指南 Spring Security 5 中的默认密码编码器。
现在我们应该通过几个快速的实时测试来验证我们的安全配置是否正确应用
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class BasicConfigurationIntegrationTest {
TestRestTemplate restTemplate;
URL base;
@LocalServerPort int port;
@Before
public void setUp() throws MalformedURLException {
restTemplate = new TestRestTemplate("user", "password");
base = new URL("https://:" + port);
}
@Test
public void whenLoggedUserRequestsHomePage_ThenSuccess()
throws IllegalStateException, IOException {
ResponseEntity<String> response =
restTemplate.getForEntity(base.toString(), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getBody().contains("Baeldung"));
}
@Test
public void whenUserWithWrongCredentials_thenUnauthorizedPage()
throws Exception {
restTemplate = new TestRestTemplate("user", "wrongpassword");
ResponseEntity<String> response =
restTemplate.getForEntity(base.toString(), String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
assertTrue(response.getBody().contains("Unauthorized"));
}
}
Spring Security 实际上是 Spring Boot Security 的基础,因此可以使用此框架或其支持的任何集成配置的所有安全配置,也可以实现到 Spring Boot 中。
5. Spring Boot OAuth2 自动配置 (使用旧版堆栈)
Spring Boot 对 OAuth2 具有专门的自动配置支持。
Spring Boot 1.x 提供的 Spring Security OAuth 支持在后续 boot 版本中被移除,取而代之的是与 Spring Security 5 捆绑在一起的一流 OAuth 支持。 我们将在下一节中了解如何使用它。
对于旧版堆栈(使用 Spring Security OAuth),我们需要先添加 Maven 依赖项来开始设置我们的应用程序
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
此依赖项包含一组能够触发在OAuth2AutoConfiguration类中定义的自动配置机制的类。
现在我们有多种选择可以继续,具体取决于我们应用程序的范围。
5.1. OAuth2 授权服务器自动配置
如果我们希望我们的应用程序成为 OAuth2 提供者,我们可以使用@EnableAuthorizationServer。
启动时,我们将注意到日志中自动配置类会为我们的授权服务器生成客户端 ID 和客户端密钥,当然还会为基本身份验证生成随机密码
Using default security password: a81cb256-f243-40c0-a585-81ce1b952a98
security.oauth2.client.client-id = 39d2835b-1f87-4a77-9798-e2975f36972e
security.oauth2.client.client-secret = f1463f8b-0791-46fe-9269-521b86c55b71
这些凭据可用于获取访问令牌
curl -X POST -u 39d2835b-1f87-4a77-9798-e2975f36972e:f1463f8b-0791-46fe-9269-521b86c55b71 \
-d grant_type=client_credentials
-d username=user
-d password=a81cb256-f243-40c0-a585-81ce1b952a98 \
-d scope=write https://:8080/oauth/token
我们的 另一篇文章 提供了有关该主题的更多详细信息。
5.2. 其他 Spring Boot OAuth2 自动配置设置
Spring Boot OAuth2 涵盖了一些其他的用例
如果我们需要我们的应用程序成为这些类型之一,我们只需要在应用程序属性中添加一些配置,如链接中详细说明的那样。
所有 OAuth2 特定属性都可以在 Spring Boot Common Application Properties 中找到。
6. Spring Boot OAuth2 自动配置 (使用新版堆栈)
要使用新版堆栈,我们需要添加基于我们想要配置的内容(授权服务器、资源服务器或客户端应用程序)的依赖项。
让我们逐一查看它们。
6.1. OAuth2 授权服务器支持
正如我们所见,Spring Security OAuth 堆栈提供了将授权服务器作为 Spring 应用程序设置的可能性。 但该项目已被弃用,并且 Spring 目前不支持其自身的授权服务器。 而是建议使用现有的成熟提供商,例如 Okta、Keycloak 和 ForgeRock。
但是,Spring Boot 使我们能够轻松配置这些提供商。 例如,有关 Keycloak 配置,我们可以参考 Spring Boot 中使用 Keycloak 的快速指南 或 Keycloak 嵌入在 Spring Boot 应用程序中。
6.2. OAuth2 资源服务器支持
要包含资源服务器的支持,我们需要添加此依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
如需获取最新信息,请访问 Maven Central。
此外,在我们的安全配置中,我们需要包含 oauth2ResourceServer() DSL
@Configuration
public class JWTSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
...
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
...
}
}
我们的 使用 Spring Security 5 的 OAuth 2.0 资源服务器 提供了对该主题的深入分析。
6.3. OAuth2 客户端支持
与配置资源服务器类似,客户端应用程序也需要其依赖项和 DSL。
这是 OAuth2 客户端支持的特定依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
最新版本可在 Maven Central 找到。
Spring Security 5 还通过其 oath2Login() DSL 提供一流的登录支持。
有关新堆栈中 SSO 支持的详细信息,请参阅我们的文章 使用 Spring Security OAuth2 实现简单的单点登录。
7. 结论
在本文中,我们重点介绍了 Spring Boot 提供的默认安全配置。我们了解了如何禁用或覆盖安全自动配置机制。然后我们研究了如何应用新的安全配置。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















