AuthLoginTest.java
12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package com.youjia.auth;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.youjia.common.constant.CommonConstants;
import com.youjia.framework.security.AuthTokenService;
import com.youjia.system.dto.RoleMenuAssignDTO;
import com.youjia.system.entity.SysMenu;
import com.youjia.system.entity.SysRole;
import com.youjia.system.entity.SysUser;
import com.youjia.system.entity.SysUserRole;
import com.youjia.system.mapper.SysMenuMapper;
import com.youjia.system.mapper.SysRoleMapper;
import com.youjia.system.mapper.SysRoleMenuMapper;
import com.youjia.system.mapper.SysUserMapper;
import com.youjia.system.mapper.SysUserRoleMapper;
import com.youjia.system.service.SysRoleService;
import com.youjia.system.support.PermissionCacheEvictor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 统一登录 / 鉴权 + 权限缓存失效(集成用例,鉴权默认开启)。
*
* <p>自带测试数据:新建一个非内置角色与两个账号,测完清理,不依赖初始 admin 密码。</p>
*
* <p>核心场景:<b>角色权限变更后,失效该角色下「在线用户」的权限缓存</b> ——
* 授权前访问被 10003 拦截,授权后(权限缓存已失效)同一令牌立刻放行。</p>
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("dev")
class AuthLoginTest {
private static final String RAW_PASSWORD = "Auth@Test2026";
private static final String PERM_ROLE_VIEW = "system:role:view";
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Autowired
private SysRoleMapper sysRoleMapper;
@Autowired
private SysRoleMenuMapper sysRoleMenuMapper;
@Autowired
private SysMenuMapper sysMenuMapper;
@Autowired
private SysRoleService sysRoleService;
@Autowired
private AuthTokenService authTokenService;
@Autowired
private PermissionCacheEvictor permissionCacheEvictor;
@Autowired
private PasswordEncoder passwordEncoder;
private final ObjectMapper objectMapper = new ObjectMapper();
private Long roleId;
private Long userId;
private String account;
private Long roleViewMenuId;
@BeforeEach
void setUp() {
String suffix = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
SysRole role = new SysRole();
role.setRoleCode("TEST_AUTH_" + suffix);
role.setRoleName("鉴权测试角色");
role.setDescription("单元测试临时角色");
role.setIsBuiltin(CommonConstants.NO);
role.setDefaultDataScope(1);
role.setSort(999);
role.setStatus(CommonConstants.STATUS_ENABLED);
sysRoleMapper.insert(role);
roleId = role.getRoleId();
SysUser user = new SysUser();
account = "auth_test_" + suffix.toLowerCase();
user.setAccount(account);
user.setName("鉴权测试账号");
user.setPassword(passwordEncoder.encode(RAW_PASSWORD));
user.setStatus(CommonConstants.STATUS_ENABLED);
user.setOrgId(CommonConstants.ROOT_ORG_ID);
user.setDataScope(1);
sysUserMapper.insert(user);
userId = user.getUserId();
SysUserRole relation = new SysUserRole();
relation.setUserId(userId);
relation.setRoleId(roleId);
sysUserRoleMapper.insert(relation);
SysMenu menu = sysMenuMapper.selectOne(new LambdaQueryWrapper<SysMenu>()
.eq(SysMenu::getPermCode, PERM_ROLE_VIEW));
assertNotNull(menu, "初始化数据应包含权限码 " + PERM_ROLE_VIEW);
roleViewMenuId = menu.getMenuId();
authTokenService.removeSessionsByUserId(userId);
authTokenService.evictPermCache(userId);
}
@AfterEach
void tearDown() {
if (userId != null) {
authTokenService.removeSessionsByUserId(userId);
authTokenService.evictPermCache(userId);
sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
sysUserMapper.deleteById(userId);
}
if (roleId != null) {
sysRoleMenuMapper.delete(new LambdaQueryWrapper<com.youjia.system.entity.SysRoleMenu>()
.eq(com.youjia.system.entity.SysRoleMenu::getRoleId, roleId));
sysRoleMapper.deleteById(roleId);
}
}
/* ------------------------------------------------------------------ 用例 */
@Test
@DisplayName("账号密码登录成功,返回令牌与身份信息")
void loginSuccess() {
JsonNode data = login(RAW_PASSWORD).path("data");
assertTrue(data.path("token").asText().length() > 10, "应返回令牌");
assertEquals(userId.longValue(), data.path("userId").asLong());
assertTrue(data.path("roleCodes").toString().contains("TEST_AUTH"));
assertTrue(authTokenService.isOnline(userId), "登录后应处于在线状态");
}
@Test
@DisplayName("密码错误登录失败,返回 20003")
void loginWithWrongPassword() {
JsonNode resp = login("wrong-password");
assertEquals(20003, resp.path("code").asInt());
assertFalse(authTokenService.isOnline(userId), "登录失败不应建立会话");
}
@Test
@DisplayName("未携带令牌访问受保护接口,返回 10002")
void accessWithoutToken() {
JsonNode resp = get("/system/role/page?current=1&size=10", null);
assertEquals(10002, resp.path("code").asInt());
}
@Test
@DisplayName("令牌无效 / 已过期,返回 10002")
void accessWithInvalidToken() {
JsonNode resp = get("/system/role/page?current=1&size=10", UUID.randomUUID().toString());
assertEquals(10002, resp.path("code").asInt());
}
@Test
@DisplayName("已登录但角色未授权该权限码,返回 10003")
void accessWithoutPermission() {
String token = login(RAW_PASSWORD).path("data").path("token").asText();
JsonNode resp = get("/system/role/page?current=1&size=10", token);
assertEquals(10003, resp.path("code").asInt());
}
@Test
@DisplayName("角色授权后,在线用户的权限缓存被失效,同一令牌立即放行(核心场景)")
void permissionChangeEvictsOnlineUserCache() {
String token = login(RAW_PASSWORD).path("data").path("token").asText();
// 1) 授权前:无权限
assertEquals(10003, get("/system/role/page?current=1&size=10", token).path("code").asInt());
// 2) 给角色配置菜单可见范围(业务入口内部会触发权限缓存失效)
RoleMenuAssignDTO dto = new RoleMenuAssignDTO();
dto.setRoleId(roleId);
dto.setMenuIds(List.of(roleViewMenuId));
sysRoleService.assignMenus(dto);
// 3) 授权后:权限缓存已失效,重新加载后立即放行
JsonNode resp = get("/system/role/page?current=1&size=10", token);
assertEquals(200, resp.path("code").asInt(), "角色授权后在线用户应立刻获得新权限:" + resp);
}
@Test
@DisplayName("权限缓存失效只统计在线用户,离线用户不计入")
void evictOnlyCountsOnlineUsers() {
String token = login(RAW_PASSWORD).path("data").path("token").asText();
// 再挂一个同角色的离线账号(只建数据、不登录)
SysUser offline = new SysUser();
offline.setAccount(account + "_off");
offline.setName("离线账号");
offline.setPassword(passwordEncoder.encode(RAW_PASSWORD));
offline.setStatus(CommonConstants.STATUS_ENABLED);
offline.setOrgId(CommonConstants.ROOT_ORG_ID);
sysUserMapper.insert(offline);
SysUserRole relation = new SysUserRole();
relation.setUserId(offline.getUserId());
relation.setRoleId(roleId);
sysUserRoleMapper.insert(relation);
try {
int evicted = permissionCacheEvictor.evictByRoleId(roleId);
assertEquals(1, evicted, "只应失效 1 个在线用户,离线账号不计入");
} finally {
authTokenService.evictPermCache(offline.getUserId());
sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
.eq(SysUserRole::getUserId, offline.getUserId()));
sysUserMapper.deleteById(offline.getUserId());
}
assertNotNull(token);
}
@Test
@DisplayName("登出后令牌失效,再次访问返回 10002")
void logoutInvalidatesToken() {
String token = login(RAW_PASSWORD).path("data").path("token").asText();
JsonNode logoutResp = post("/system/auth/logout", "{}", token);
assertEquals(200, logoutResp.path("code").asInt());
assertFalse(authTokenService.isOnline(userId), "登出后不应再有在线终端");
assertEquals(10002, get("/system/role/page?current=1&size=10", token).path("code").asInt());
}
@Test
@DisplayName("当前登录用户信息接口返回角色与权限码")
void currentUserInfo() {
String token = login(RAW_PASSWORD).path("data").path("token").asText();
RoleMenuAssignDTO dto = new RoleMenuAssignDTO();
dto.setRoleId(roleId);
dto.setMenuIds(List.of(roleViewMenuId));
sysRoleService.assignMenus(dto);
authTokenService.evictPermCache(userId);
JsonNode data = get("/system/auth/info", token).path("data");
assertEquals(account, data.path("account").asText());
assertTrue(data.path("permCodes").toString().contains(PERM_ROLE_VIEW));
assertEquals(1, data.path("dataScope").asInt());
}
/* -------------------------------------------------------------- 辅助方法 */
private JsonNode login(String password) {
ObjectNode body = objectMapper.createObjectNode();
body.put("account", account);
body.put("password", password);
return post("/system/auth/login", body.toString(), null);
}
private JsonNode get(String path, String token) {
HttpHeaders headers = new HttpHeaders();
if (token != null) {
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
}
ResponseEntity<String> response = restTemplate.exchange(
path, HttpMethod.GET, new HttpEntity<>(headers), String.class);
return parse(response.getBody());
}
private JsonNode post(String path, String jsonBody, String token) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
if (token != null) {
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
}
ResponseEntity<String> response = restTemplate.exchange(
path, HttpMethod.POST, new HttpEntity<>(jsonBody, headers), String.class);
return parse(response.getBody());
}
private JsonNode parse(String body) {
try {
return objectMapper.readTree(body == null ? "{}" : body);
} catch (Exception e) {
return objectMapper.createObjectNode();
}
}
}