fix(auth): 登录不再推进会话世代,支持同账号多端同时在线
产品定档同账号可多端同时在线:登录 +1 会让每次登录都吊销其他端 token。 - 移除登录路径的 session_epoch 自增;登出仍原子 +1 吊销全部旧令牌 - 改密补 session_epoch +1,避免旧 token 继续用到 7 天 TTL - 单设备开关仍可按 machine 顶下线(现网默认关闭)
This commit is contained in:
+2
@@ -458,6 +458,8 @@ public class AdminUserService {
|
||||
throw new BusinessException("密码至少6个字符");
|
||||
}
|
||||
update.set(AdminUserEntity::getPasswordHash, passwordEncoder.hash(password));
|
||||
// 登录不再推进世代后,改密必须自己吊销所有已发令牌:否则旧 token 能用到 7 天 TTL
|
||||
update.setSql("session_epoch = session_epoch + 1");
|
||||
dirty = true;
|
||||
}
|
||||
if (wantRole != null && !wantRole.isEmpty()) {
|
||||
|
||||
+3
-2
@@ -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());
|
||||
|
||||
+42
@@ -1,5 +1,8 @@
|
||||
package com.nanri.aiimage.modules.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
||||
@@ -11,6 +14,8 @@ import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdate
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -30,6 +35,13 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class AdminUserServiceTest {
|
||||
|
||||
@BeforeAll
|
||||
static void initMybatisMetadata() {
|
||||
// LambdaUpdateWrapper 列名解析需要 TableInfo 缓存;mock 环境不会自动注册
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserStoresSuppliedDirectPermissionsInSameTransactionalMethod() throws Exception {
|
||||
AdminUserMapper userMapper = mock(AdminUserMapper.class);
|
||||
@@ -77,6 +89,36 @@ class AdminUserServiceTest {
|
||||
.isAnnotationPresent(Transactional.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPasswordAdvancesSessionEpoch() {
|
||||
// 登录不再推进世代(多端同时在线)后,改密必须吊销所有旧 token,否则能用到 7 天 TTL
|
||||
AdminUserMapper userMapper = mock(AdminUserMapper.class);
|
||||
WerkzeugPasswordEncoder passwordEncoder = mock(WerkzeugPasswordEncoder.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||
AdminUserService service = new AdminUserService(
|
||||
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService,
|
||||
mock(CompanyService.class));
|
||||
AdminUserEntity operator = user(10L, "admin", 1, null);
|
||||
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setPassword("newpass1");
|
||||
|
||||
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||
when(permissionService.hasAnyAdminMenu(eq(operator), any())).thenReturn(true);
|
||||
when(userMapper.selectById(20L)).thenReturn(target);
|
||||
when(passwordEncoder.hash("newpass1")).thenReturn("hashed");
|
||||
|
||||
service.updateUser(operator, 20L, request);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaUpdateWrapper<AdminUserEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(userMapper).update(any(), captor.capture());
|
||||
assertThat(captor.getValue().getSqlSet()).contains("session_epoch = session_epoch + 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserCanReplaceOnlyDirectPermissionsTransactionally() throws Exception {
|
||||
AdminUserMapper userMapper = mock(AdminUserMapper.class);
|
||||
|
||||
+9
-11
@@ -60,9 +60,9 @@ class AuthServiceTest {
|
||||
|
||||
// 绑定写入当前设备(last-login-wins),签发的 token 也用当前设备
|
||||
verify(f.loginUserMapper, times(1)).update(any(), any());
|
||||
verify(f.loginUserMapper).incrementSessionEpoch(7L);
|
||||
// 登录推进世代(0 → 1),新令牌必须签上推进后的值
|
||||
verify(f.jwtService).issue(7L, "u7", "devB", 1L);
|
||||
// 2026-10-26:登录不再推进世代,多端同时在线;旧令牌只由登出/改密吊销
|
||||
verify(f.loginUserMapper, never()).incrementSessionEpoch(anyLong());
|
||||
verify(f.jwtService).issue(7L, "u7", "devB", 0L);
|
||||
assertThat(vo.getDeviceId()).isEqualTo("devB");
|
||||
}
|
||||
|
||||
@@ -107,16 +107,13 @@ class AuthServiceTest {
|
||||
// ---------- check_login:被顶下线必须拦截且不续期 ----------
|
||||
|
||||
@Test
|
||||
void loginSignsTokenWithSessionEpochReadBackFromDatabase() {
|
||||
// CR-07:并发登录时库里的世代可能已被另一路推到 N+2;内存 +1 会签出 stale token,
|
||||
// 登录成功后第一次请求立刻 401。令牌必须用自增后回读到的库值。
|
||||
Fixture f = fixture(true);
|
||||
void loginKeepsStoredSessionEpochForConcurrentSessions() {
|
||||
// 2026-10-26「同账号多端同时在线」:登录不再自增世代,令牌直接签当前库值,
|
||||
// 另一端的旧 token 不会被新登录顶掉;吊销只由登出/改密推进。
|
||||
Fixture f = fixture(false);
|
||||
LoginUserEntity user = f.user("devA");
|
||||
user.setSessionEpoch(0L);
|
||||
LoginUserEntity refreshed = f.user("devA");
|
||||
refreshed.setSessionEpoch(41L);
|
||||
user.setSessionEpoch(41L);
|
||||
when(f.loginUserMapper.selectOne(any())).thenReturn(user);
|
||||
when(f.loginUserMapper.selectById(7L)).thenReturn(refreshed);
|
||||
when(f.passwordEncoder.matches("pwd", "hash")).thenReturn(true);
|
||||
when(f.jwtService.issue(eq(7L), anyString(), anyString(), anyLong())).thenReturn("jwt-token");
|
||||
|
||||
@@ -128,6 +125,7 @@ class AuthServiceTest {
|
||||
f.service.login(request);
|
||||
|
||||
verify(f.jwtService).issue(7L, "u7", "devB", 41L);
|
||||
verify(f.loginUserMapper, never()).incrementSessionEpoch(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user