fix(登出): logout 此前只清 cookie——现写 machine 吊销标记且先于超管豁免
吊销必须挂在 assertSameDevice 之前:那条路径第一行就是 if (exempt) return;, 放它下面等于超管永不见吊销。也不能清空 machine(本类对空值是「尚未绑定=放行」语义)。 前缀避开 claude-*/e2e-*:users.machine 还被当测试号签名用。写值带 deviceId 做 CAS, 不把别处刚登录的新会话一起打死。
This commit is contained in:
@@ -19,6 +19,15 @@ public final class DeviceSessionPolicy {
|
|||||||
/** 账号已在其他设备登录(前端据此提示并下线本设备)。 */
|
/** 账号已在其他设备登录(前端据此提示并下线本设备)。 */
|
||||||
public static final int CODE_KICKED = 4011;
|
public static final int CODE_KICKED = 4011;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登出吊销标记:写进 {@code users.machine},让该设备已发的令牌下一请求即拒。
|
||||||
|
*
|
||||||
|
* <p>不能用「清空 machine」表达登出——本类对空 machine 是<b>放行</b>语义
|
||||||
|
* (尚未绑定不做限制,见 {@link #assertSameDevice}),清空只会放宽。前缀也必须与
|
||||||
|
* 测试号签名 {@code claude-*} / {@code e2e-*} 不重叠,否则清脏数据脚本会把已登出设备读成测试号。</p>
|
||||||
|
*/
|
||||||
|
public static final String REVOKED_PREFIX = "revoked@";
|
||||||
|
|
||||||
private DeviceSessionPolicy() {
|
private DeviceSessionPolicy() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,6 +117,26 @@ public final class DeviceSessionPolicy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** 这张 machine 值是不是登出吊销标记。 */
|
||||||
|
public static boolean isRevoked(String machine) {
|
||||||
|
String value = machine == null ? "" : machine.trim();
|
||||||
|
return value.startsWith(REVOKED_PREFIX);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 吊销校验。<b>必须挂在 {@link #assertSameDevice} 之前调用</b>:那条路径第一行就是
|
||||||
|
* {@code if (exempt) return;}(超管豁免),把吊销放在它下面等于超管永不见吊销。
|
||||||
|
* 也不受 singleDevice 开关支配——登出了就该拒,与开关无关。
|
||||||
|
*/
|
||||||
|
public static void assertNotRevoked(String storedMachine, Long userId, String username) {
|
||||||
|
if (isRevoked(storedMachine)) {
|
||||||
|
log.warn("[auth] 会话已登出被拒 userId={} username={}", userId, username);
|
||||||
|
// 文案沿用既有 401:客户端只按 401/409 分支,新文案会让它走未知路径
|
||||||
|
throw new BusinessException(401, "登录已过期,请重新登录");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 登录绑定时的中文日志:首次绑定 / 换设备(顶下线)/ 同设备重登,便于线上排查互踢来源。 */
|
/** 登录绑定时的中文日志:首次绑定 / 换设备(顶下线)/ 同设备重登,便于线上排查互踢来源。 */
|
||||||
public static void logBindOnLogin(String previousMachine, String deviceId, Long userId, String username) {
|
public static void logBindOnLogin(String previousMachine, String deviceId, Long userId, String username) {
|
||||||
String previous = previousMachine == null ? "" : previousMachine.trim();
|
String previous = previousMachine == null ? "" : previousMachine.trim();
|
||||||
|
|||||||
+3
-1
@@ -52,7 +52,9 @@ public class LoginController {
|
|||||||
|
|
||||||
@PostMapping("/logout")
|
@PostMapping("/logout")
|
||||||
@Operation(summary = "登出")
|
@Operation(summary = "登出")
|
||||||
public ResponseEntity<ApiResponse<Void>> logout() {
|
public ResponseEntity<ApiResponse<Void>> logout(HttpServletRequest request) {
|
||||||
|
// 先吊销服务端会话,再清 cookie:反过来的话,客户端留着旧令牌仍能打到内部接口
|
||||||
|
authService.logoutByToken(resolveToken(request));
|
||||||
ResponseCookie cookie = authService.buildClearCookie();
|
ResponseCookie cookie = authService.buildClearCookie();
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.header(HttpHeaders.SET_COOKIE, cookie.toString())
|
.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 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 LoginUserMapper loginUserMapper;
|
||||||
private final WerkzeugPasswordEncoder passwordEncoder;
|
private final WerkzeugPasswordEncoder passwordEncoder;
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
@@ -125,6 +128,45 @@ public class AuthService {
|
|||||||
return buildResult(user, deviceId, isAdmin);
|
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) {
|
public LoginResultVo checkLogin(String token, String currentDeviceId) {
|
||||||
if (token == null || token.isBlank()) {
|
if (token == null || token.isBlank()) {
|
||||||
throw new BusinessException(401, "未登录");
|
throw new BusinessException(401, "未登录");
|
||||||
|
|||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
package com.nanri.aiimage.common.security;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
|
import static org.assertj.core.api.Assertions.catchThrowableOfType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登出必须真能吊销。今天 {@code POST /logout} 只清 cookie(LoginController),服务端不留任何痕迹,
|
||||||
|
* 已发令牌在 7 天内继续有效。吊销借 {@code users.machine} 写一个不可匹配的标记——
|
||||||
|
* 而「清空 machine」在这个类里是【放行】语义(尚未绑定不做限制),所以不能用空串表达登出。
|
||||||
|
*/
|
||||||
|
class DeviceSessionRevocationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void revokedMarkerIsRecognised() {
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked("revoked@12#20261009120000")).isTrue();
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked(" revoked@12#20261009120000 ")).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void revokedMarkerRejectsWithTheSameMessageClientsAlreadyHandle() {
|
||||||
|
BusinessException e = catchThrowableOfType(
|
||||||
|
() -> DeviceSessionPolicy.assertNotRevoked("revoked@12#20261009120000", 12L, "超管"),
|
||||||
|
BusinessException.class);
|
||||||
|
assertThat(e).isNotNull();
|
||||||
|
assertThat(e.getCode()).isEqualTo(401);
|
||||||
|
// 客户端只按 401/409 分支;换新文案会让它走未知路径
|
||||||
|
assertThat(e.getMessage()).isEqualTo("登录已过期,请重新登录");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blankMachineIsNotRevocation() {
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked("")).isFalse();
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked(null)).isFalse();
|
||||||
|
assertThatCode(() -> DeviceSessionPolicy.assertNotRevoked("", 1L, "u")).doesNotThrowAnyException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAccountSignaturesAreNotRevokedMarkers() {
|
||||||
|
// users.machine 同时被当测试号签名使用(claude-*/e2e-*,10-06 清脏数据靠它认账号):
|
||||||
|
// 吊销标记的前缀必须与这两族写法不重叠,否则清账脚本会把已登出设备读成测试号(或反之)。
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked("claude-abc")).isFalse();
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked("e2e-device-1")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void realDeviceIdIsNotRevoked() {
|
||||||
|
assertThat(DeviceSessionPolicy.isRevoked(
|
||||||
|
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")).isFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user