fix(auth): 登录不再推进会话世代,支持同账号多端同时在线

产品定档同账号可多端同时在线:登录 +1 会让每次登录都吊销其他端 token。
- 移除登录路径的 session_epoch 自增;登出仍原子 +1 吊销全部旧令牌
- 改密补 session_epoch +1,避免旧 token 继续用到 7 天 TTL
- 单设备开关仍可按 machine 顶下线(现网默认关闭)
This commit is contained in:
2026-10-26 15:13:43 +08:00
parent 2163c6b585
commit 915a573439
5 changed files with 59 additions and 40 deletions
@@ -9,8 +9,9 @@ import org.apache.ibatis.annotations.Param;
public interface LoginUserMapper extends BaseMapper<LoginUserEntity> {
/**
* 会话世代 +1(登录、登出各调用一次)。原子自增而不是「读出来再写回」:
* 双节点同时登录时后者不能把前者的世代覆盖回去。返回 0 行表示用户已不存在。
* 会话世代 +1(登出、改密时调用;登录不再推进,见 2026-10-26「多端同时在线」定档)。
* 原子自增而不是「读出来再写回」:双节点并发吊销时后者不能把前者的世代覆盖回去。
* 返回 0 行表示用户已不存在。
*/
int incrementSessionEpoch(@Param("userId") Long userId);
}
@@ -116,7 +116,8 @@ public class AuthService {
accountExpiryService.assertLoginAllowed(user);
boolean isAdmin = user.getIsAdmin() != null && user.getIsAdmin() == 1;
advanceSessionEpoch(user);
// 2026-10-26 产品定档「同账号可多端同时在线」:登录不再推进 session_epoch。
// 旧令牌只由登出/改密推进世代吊销;单设备开关仍可按 machine 顶下线(默认关闭)。
// 单设备登录:登录成功即把账号绑定到当前设备(last-login-wins),原设备下一次请求被顶下线
if (authProperties.isSingleDeviceEnabled()) {
DeviceSessionPolicy.logBindOnLogin(user.getMachine(), deviceId, user.getId(), user.getUsername());
@@ -126,7 +127,7 @@ public class AuthService {
} else if (DeviceSessionPolicy.isRevoked(user.getMachine())) {
// 开关关掉后登录不再写 machine,登出留下的吊销标记就没人清:此后每次登录都会先成功、
// 再被 requireUser 的 assertNotRevoked 判成「登录已过期」,账号永久锁死。
// 登录成功即视为新会话(上面已推进 session_epoch,旧令牌另有世代校验兜底),
// 登录成功即视为新会话(登出已推进世代,旧令牌另有世代校验兜底),
// 清空标记(空=未绑定,放行语义);仍不写设备号。
log.warn("[auth] 登录清除登出吊销标记 userId={} username={}", user.getId(), user.getUsername());
loginUserMapper.update(null, new LambdaUpdateWrapper<LoginUserEntity>()
@@ -260,31 +261,6 @@ public class AuthService {
return authProperties.getCookieName();
}
/**
* 登录推进世代;返回 0 行说明用户行已消失,不能再签发一个「世代比库还新」的令牌。
*
* <p>CR-07:自增用原子 UPDATE,但令牌必须按<b>回读到的库值</b>签发。两路并发登录
* 都读到 N 时,库里会被推到 N+2;若各自按内存 N+1 签,两张 token 都落后一代,
* 登录成功后第一次请求就被 session_epoch 校验打成 401。回读牺牲「两张 token 世代
* 完全相同」的极端情形,换取任何一张都不会低于库值。</p>
*/
private void advanceSessionEpoch(LoginUserEntity user) {
int updated = loginUserMapper.incrementSessionEpoch(user.getId());
if (updated != 1) {
log.warn("[auth] 登录推进会话世代失败 userId={} updated={}", user.getId(), updated);
throw new BusinessException(500, "登录状态更新失败,请重试");
}
LoginUserEntity refreshed = loginUserMapper.selectById(user.getId());
if (refreshed != null && refreshed.getSessionEpoch() != null) {
user.setSessionEpoch(refreshed.getSessionEpoch());
return;
}
// 自增已成功却回读不到(极端主从延迟/半提交):退回内存 +1 只作防御,
// 不掩盖问题——下一轮校验会按库值把 stale token 拒掉。
long current = user.getSessionEpoch() == null ? 0L : user.getSessionEpoch();
user.setSessionEpoch(current + 1);
}
private LoginResultVo buildResult(LoginUserEntity user, String deviceId, boolean isAdmin) {
String token = jwtService.issue(user.getId(), user.getUsername(), deviceId,
user.getSessionEpoch() == null ? 0L : user.getSessionEpoch());