Java 后端 / 系统课时
测试安全规则
测试安全规则
本课把安全需求转化为可自动验证的状态码与响应结果。你将使用 MockMvc、@WithMockUser 和模拟 JWT,覆盖匿名访问、已认证访问、角色不足与管理员访问,避免安全配置变更后出现接口误开放或合法请求被拒绝。
学习目标
- 为公开接口、受保护接口和方法级授权建立测试矩阵
- 使用 Spring Security Test 模拟用户与 JWT 权限
- 区分 401、403 以及 CSRF 导致的失败
安全测试的判定矩阵
安全测试不应只验证“能访问”,还要验证“谁不能访问”。公开接口允许匿名访问;受保护接口在未认证时返回 401;已经认证但权限不足时返回 403;满足角色规则后才返回业务响应。
| 场景 | 模拟身份 | 预期状态 |
|---|---|---|
| 公开接口 | 匿名 | 200 |
| 个人接口 | 匿名 | 401 |
| 个人接口 | 任意已认证 JWT | 200 |
| 管理接口 | ROLE_USER |
403 |
| 管理接口 | ROLE_ADMIN |
200 |
准备安全规则
项目需要 Web、Security、OAuth2 Resource Server 和测试依赖。spring-security-test 提供 MockMvc 请求后处理器以及 @WithMockUser。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>下面的安全配置允许匿名访问 /api/public/**,其余请求必须认证;@EnableMethodSecurity 负责启用控制器方法上的 @PreAuthorize。
package com.example.demo.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}控制器同时包含公开接口、仅要求登录的接口,以及要求管理员角色的方法级授权接口。
package com.example.demo.web;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class DemoController {
@GetMapping("/public/ping")
public String ping() {
return "pong";
}
@GetMapping("/profile")
public String profile() {
return "profile";
}
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/report")
public String report() {
return "report";
}
}使用 MockMvc 模拟身份
@WebMvcTest 只加载 MVC 相关组件,测试速度比完整应用上下文更快。jwt() 不需要生成或签名真实令牌,而是直接构造经过认证的 JWT 身份;authorities 用于精确控制授权结果。
package com.example.demo.web;
import com.example.demo.security.SecurityConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(DemoController.class)
@Import(SecurityConfig.class)
class SecurityRuleTest {
@Autowired
MockMvc mockMvc;
@Test
void publicEndpointAllowsAnonymous() throws Exception {
mockMvc.perform(get("/api/public/ping"))
.andExpect(status().isOk())
.andExpect(content().string("pong"));
}
@Test
void protectedEndpointRejectsAnonymous() throws Exception {
mockMvc.perform(get("/api/profile"))
.andExpect(status().isUnauthorized());
}
@Test
void protectedEndpointAcceptsJwt() throws Exception {
mockMvc.perform(get("/api/profile")
.with(jwt().jwt(token -> token.subject("alice"))))
.andExpect(status().isOk())
.andExpect(content().string("profile"));
}
@Test
@WithMockUser(username = "alice", roles = "USER")
void adminEndpointRejectsUserRole() throws Exception {
mockMvc.perform(get("/api/admin/report"))
.andExpect(status().isForbidden());
}
@Test
void adminEndpointAcceptsAdminRole() throws Exception {
mockMvc.perform(get("/api/admin/report")
.with(jwt().authorities(
new SimpleGrantedAuthority("ROLE_ADMIN")
)))
.andExpect(status().isOk())
.andExpect(content().string("report"));
}
}预期结果:五个请求分别得到 200、401、200、403 和 200,响应体与测试断言一致。
这里同时验证了 URL 级认证和方法级角色判断。若删除 @EnableMethodSecurity,最后两个管理接口测试会暴露方法授权未生效的问题。
运行与验证
执行当前安全测试类。
./mvnw -Dtest=SecurityRuleTest test预期输出:
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS测试报告中的耗时和日志顺序属于动态值,实际结果可能不同。只要五个场景全部通过,就说明当前安全规则符合测试矩阵。
关键边界
401 表示请求尚未建立有效身份,403 表示身份已经存在但权限不足。角色快捷方法会自动添加 ROLE_ 前缀,因此 .roles("ADMIN") 对应 ROLE_ADMIN;使用 .authorities(...) 时必须写完整权限名。
本例只测试 GET 请求,因此关闭 CSRF 不影响结论。生产项目若保留 CSRF,测试 POST、PUT、PATCH 或 DELETE 时应在 MockMvc 请求中添加 .with(csrf()),否则可能得到 403,但根因并不是业务权限不足。JWT 测试应关注声明到权限的转换规则;若生产系统从 scope 或自定义 claim 生成权限,还要为对应转换器增加独立测试。