身份认证与应用安全 / 系统课时
为认证链路补齐自动化测试
为认证链路补齐自动化测试
认证功能真正容易回归的并不是“能不能登录”,而是错误密码、过期 Token、刷新轮换、退出后的会话状态与权限拒绝等边界。本节把这些行为固化成可重复执行的测试合同,让安全配置或 JWT 逻辑变化后能立即发现问题。
学习目标
- 为登录、过期、刷新、退出和权限拒绝建立明确断言
- 使用 Spring Boot Test 与
MockMvc覆盖关键认证路径 - 控制测试账号、Token 状态和时间因素,减少认证测试的随机失败
先把认证行为写成测试合同
自动化测试首先要回答“什么结果才算正确”。不要只断言 HTTP 状态码,还要检查 Token 是否返回、旧凭证是否失效,以及 401 与 403 是否被正确区分。
| 场景 | 操作 | 核心断言 |
|---|---|---|
| 密码错误 | 正确账号配错误密码登录 | 返回 401,不返回 Token |
| 登录成功 | 使用有效账号密码登录 | 返回 200,获得 Access Token 与 Refresh Token |
| Token 过期 | 携带过期 Access Token 访问受保护接口 | 返回 401 |
| 刷新轮换 | 使用 Refresh Token 刷新后再次使用旧 Token | 第一次成功,旧 Refresh Token 随后失败 |
| 主动退出 | 登录后退出,再使用原 Refresh Token | 刷新失败 |
| 权限不足 | 普通用户访问管理员接口 | 身份已认证,但返回 403 |
退出场景需要按系统真实语义断言。纯无状态 JWT 如果只撤销 Refresh Token,已经签发的 Access Token 通常会继续有效到过期;只有实现黑名单、会话版本等撤销机制时,才应该测试退出后 Access Token 立即失效。
准备稳定的测试环境
认证测试应使用独立的 test Profile、固定测试账号、测试专用签名密钥,以及隔离的数据库或缓存。测试中不要连接开发环境的共享数据,否则一个手工修改的用户状态就可能让整个认证测试集失去可重复性。
如果项目尚未加入 Spring Security 的测试支持,可以在由 Spring Boot 管理依赖版本的 Maven 项目中加入测试依赖:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>该依赖只进入测试 classpath,可用于让 MockMvc 按真实 Spring Security 过滤器链发送请求。添加后可通过 Maven 测试阶段验证依赖是否正确加载。
过期 Token 测试尤其不要依赖几秒甚至几十秒的 Thread.sleep。更稳定的方案是让 JWT 时间判断通过 Clock 获取当前时间,测试时控制时钟;或者让测试夹具使用测试签名密钥生成一个 exp 已位于过去的合法 Token。
覆盖六条关键认证路径
下面是 片段示例,依赖当前项目已经存在 /api/auth/login、/api/auth/refresh、/api/auth/logout、/api/profile 和 /api/admin/ping,并提供测试夹具 TokenFixtures 生成签名正确的过期 Access Token。请按项目实际接口路径、请求字段和夹具类名替换。
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@SpringBootTest
@ActiveProfiles("test")
class JwtAuthenticationFlowTest {
private static final String LOGIN_OK =
"{\"username\":\"alice\",\"password\":\"test-password\"}";
private static final String LOGIN_BAD =
"{\"username\":\"alice\",\"password\":\"wrong\"}";
@Autowired
WebApplicationContext context;
@Autowired
TokenFixtures tokenFixtures;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
void wrongPasswordReturns401() throws Exception {
mvc.perform(post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(LOGIN_BAD))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.accessToken").doesNotExist())
.andExpect(jsonPath("$.refreshToken").doesNotExist());
}
@Test
void loginReturnsBothTokens() throws Exception {
mvc.perform(post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(LOGIN_OK))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accessToken").isString())
.andExpect(jsonPath("$.refreshToken").isString());
}
@Test
void expiredAccessTokenReturns401() throws Exception {
String expired = tokenFixtures.expiredAccessToken("alice", "ROLE_USER");
mvc.perform(get("/api/profile")
.header("Authorization", "Bearer " + expired))
.andExpect(status().isUnauthorized());
}
@Test
void refreshTokenIsRotated() throws Exception {
String oldRefresh = field(loginAsAlice(), "refreshToken");
MvcResult refreshed = mvc.perform(post("/api/auth/refresh")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"refreshToken\":\"" + oldRefresh + "\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accessToken").isString())
.andExpect(jsonPath("$.refreshToken").isString())
.andReturn();
String newRefresh = field(refreshed, "refreshToken");
assertNotEquals(oldRefresh, newRefresh);
mvc.perform(post("/api/auth/refresh")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"refreshToken\":\"" + oldRefresh + "\"}"))
.andExpect(status().isUnauthorized());
}
@Test
void logoutRevokesRefreshSession() throws Exception {
MvcResult login = loginAsAlice();
String access = field(login, "accessToken");
String refresh = field(login, "refreshToken");
mvc.perform(post("/api/auth/logout")
.header("Authorization", "Bearer " + access))
.andExpect(status().isNoContent());
mvc.perform(post("/api/auth/refresh")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"refreshToken\":\"" + refresh + "\"}"))
.andExpect(status().isUnauthorized());
}
@Test
void normalUserCannotAccessAdminEndpoint() throws Exception {
String access = field(loginAsAlice(), "accessToken");
mvc.perform(get("/api/admin/ping")
.header("Authorization", "Bearer " + access))
.andExpect(status().isForbidden());
}
private MvcResult loginAsAlice() throws Exception {
return mvc.perform(post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(LOGIN_OK))
.andExpect(status().isOk())
.andReturn();
}
private String field(MvcResult result, String name) throws Exception {
String body = result.getResponse().getContentAsString();
return JsonPath.read(body, "$." + name);
}
}这组测试要求测试环境提前创建 alice,密码为 test-password,并授予普通用户角色。TokenFixtures 应使用与测试环境一致的签名算法和密钥,只改变 Token 的时间声明;这样测试的是“过期令牌被真实过滤器拒绝”,而不是绕过认证逻辑直接模拟异常。
运行测试并核对结果
完成接口路径和测试数据适配后,只运行这一组认证测试,可以快速确认六条安全路径是否同时成立。
./mvnw -Dtest=JwtAuthenticationFlowTest test预期输出
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS实际 Maven 日志中的耗时和其他构建信息可能不同;验收重点是六个测试全部通过且构建成功。如果认证依赖数据库、Redis 等基础设施,应使用 Testcontainers 或独立测试实例,使每次执行都从可预测状态开始。
让测试真正能发现回归
认证测试不要把动态时间戳、随机 Token 字符串、随机 ID 或完整错误文案写死。应断言稳定的安全语义,例如状态码、必要字段是否存在、旧 Refresh Token 是否失效以及权限边界是否正确。
当 SecurityFilterChain、JWT 校验、刷新轮换、退出策略或角色映射发生修改时,这六条路径应作为最小回归集持续执行。它们分别守住凭证校验、令牌生命周期、会话撤销和授权边界,比只测试一次登录成功更容易及时暴露认证链路中的破坏性改动。