baeldung 2024-02-29
1. 概述
在本教程中,我们将探讨 Spring Boot 在安全方面的“约定优于配置”(opinionated)方式。
简而言之,我们将重点关注默认的安全配置,以及在需要时如何禁用或自定义该配置。
2. 默认安全设置
为了给我们的 Spring Boot 应用添加安全功能,我们需要添加安全启动器依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
这将同时引入包含初始/默认安全配置的 SecurityAutoConfiguration 类。
注意:这里我们没有指定版本号,因为我们假设项目已经使用 Spring Boot 作为父项目。
默认情况下,应用程序会启用身份认证(Authentication)。此外,Spring Boot 还会通过内容协商(content negotiation)来决定使用 HTTP Basic 认证还是表单登录(formLogin)。
Spring Boot 提供了一些预定义的属性:
spring.security.user.name
spring.security.user.password
如果我们未通过 spring.security.user.password 属性配置密码,并启动应用,系统会自动生成一个随机密码并打印到控制台日志中:
Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6
更多默认配置,请参阅 Spring Boot 常见应用属性参考页面 中的安全属性部分。
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 允许我们通过添加新的自定义配置类来覆盖(override)自动配置的安全设置。这种方式通常更简单,因为我们只是在现有安全配置的基础上进行定制以满足需求。
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 对密码进行编码。
现在,我们可以通过几个简单的集成测试来验证安全配置是否生效:
@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("http://localhost:" + 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 Boot Security 背后就是 Spring Security,因此任何 Spring Security 支持的安全配置或集成,都可以在 Spring Boot 中实现。
5. Spring Boot OAuth2 自动配置(使用旧版堆栈)
Spring Boot 为 OAuth2 提供了专门的自动配置支持。
Spring Boot 1.x 中使用的 Spring Security OAuth 支持已在后续版本中被移除,取而代之的是 Spring Security 5 内置的一等公民(first-class)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 http://localhost:8080/oauth/token
更多详细信息,请参阅我们的另一篇文章。
5.2 其他 Spring Boot OAuth2 自动配置选项
Spring Boot OAuth2 还支持以下其他用例:
- 资源服务器(Resource Server)—— 使用
@EnableResourceServer - 客户端应用(Client Application)—— 使用
@EnableOAuth2Sso或@EnableOAuth2Client
如果需要将应用配置为上述类型之一,只需在 application.properties 中添加相应配置即可,具体细节请参阅相关链接。
所有 OAuth2 相关属性均可在 Spring Boot 常见应用属性 页面找到。
6. Spring Boot OAuth2 自动配置(使用新版堆栈)
要使用新版堆栈,我们需要根据目标(授权服务器、资源服务器或客户端应用)添加相应的依赖。
下面逐一介绍。
6.1 OAuth2 授权服务器支持
如前所述,Spring Security OAuth 堆栈曾允许我们将 Spring 应用配置为授权服务器。但该项目已被弃用,目前 Spring 官方不再维护自己的授权服务器实现。官方建议使用成熟稳定的第三方提供商,如 Okta、Keycloak 和 ForgeRock。
不过,Spring Boot 使集成这些提供商变得非常简单。关于 Keycloak 的配置示例,可参考以下文章:
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 还通过 oauth2Login() DSL 提供了一流的登录支持。
7. 结论
本文重点介绍了 Spring Boot 提供的默认安全配置。我们探讨了如何禁用或覆盖安全自动配置机制,并展示了如何应用新的安全配置。