fix(登出): logout 此前只清 cookie——现写 machine 吊销标记且先于超管豁免

吊销必须挂在 assertSameDevice 之前:那条路径第一行就是 if (exempt) return;,
放它下面等于超管永不见吊销。也不能清空 machine(本类对空值是「尚未绑定=放行」语义)。
前缀避开 claude-*/e2e-*:users.machine 还被当测试号签名用。写值带 deviceId 做 CAS,
不把别处刚登录的新会话一起打死。
This commit is contained in:
2026-10-09 14:48:11 +08:00
parent d349bc1a7d
commit 3f5f081cb5
4 changed files with 128 additions and 1 deletions
@@ -52,7 +52,9 @@ public class LoginController {
@PostMapping("/logout")
@Operation(summary = "登出")
public ResponseEntity<ApiResponse<Void>> logout() {
public ResponseEntity<ApiResponse<Void>> logout(HttpServletRequest request) {
// 先吊销服务端会话,再清 cookie:反过来的话,客户端留着旧令牌仍能打到内部接口
authService.logoutByToken(resolveToken(request));
ResponseCookie cookie = authService.buildClearCookie();
return ResponseEntity.ok()
.header(HttpHeaders.SET_COOKIE, cookie.toString())
@@ -34,6 +34,9 @@ public class AuthService {
private static final DateTimeFormatter EXPIRES_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
/** 吊销标记里的时间戳:只为让每次登出的值唯一,不参与任何判定。 */
private static final DateTimeFormatter REVOKE_STAMP = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private final LoginUserMapper loginUserMapper;
private final WerkzeugPasswordEncoder passwordEncoder;
private final JwtService jwtService;
@@ -125,6 +128,45 @@ public class AuthService {
return buildResult(user, deviceId, isAdmin);
}
/**
* 登出=吊销这台设备已发的令牌。今天 {@code POST /logout} 只清 cookie,服务端不留痕迹,
* 令牌在 7 天 TTL 内继续可用。
*
* <p>写成不可匹配的标记而不是清空:见 {@link DeviceSessionPolicy#REVOKED_PREFIX} 的注释。
* 带 deviceId 条件(CAS):只吊销「这台设备仍是当前绑定」的那次会话,避免把别处刚登录的
* 新会话一起打死。deviceId 为空则退化为按 userId 吊销。</p>
*/
public void logout(Long userId, String deviceId) {
if (userId == null) {
return;
}
String marker = DeviceSessionPolicy.REVOKED_PREFIX + userId + "#"
+ java.time.LocalDateTime.now().format(REVOKE_STAMP);
String bound = deviceId == null ? "" : deviceId.trim();
int updated = loginUserMapper.update(null, new LambdaUpdateWrapper<LoginUserEntity>()
.set(LoginUserEntity::getMachine, marker)
.eq(LoginUserEntity::getId, userId)
.eq(!bound.isEmpty(), LoginUserEntity::getMachine, bound));
log.info("[auth] 登出吊销 userId={} deviceBound={} updated={}", userId, bound, updated);
}
/** 从令牌里取出身份再吊销;解析不出(已过期/伪造)就什么都不做——cookie 由调用方清。 */
public void logoutByToken(String token) {
if (token == null || token.isBlank()) {
return;
}
io.jsonwebtoken.Claims claims = jwtService.parse(token);
if (claims == null) {
return;
}
try {
logout(Long.parseLong(claims.getSubject()), DeviceSessionPolicy.claimDeviceId(claims));
} catch (NumberFormatException e) {
log.warn("[auth] 登出时 subject 不是数字,忽略");
}
}
public LoginResultVo checkLogin(String token, String currentDeviceId) {
if (token == null || token.isBlank()) {
throw new BusinessException(401, "未登录");