F2-6: JWT 瘦身——roles 不入 claims,RoleResolver 服务端缓存解析
- JwtService.issue() 移除 CLAIM_ROLES,token 仅携带 userId/account/name/depart/org - JwtService.parse() roles 固定返回空列表(由 RoleResolver 填充) - 新增 RoleResolver:Caffeine 缓存 userId→roles,TTL 5 分钟,容量 5000 SQL 与 SysUserService 同源(sys_usergrouprole⋈sys_usergroupuser) DB 不可达时降级为空列表,不阻断请求 - JwtAuthFilter:parse 后调 RoleResolver 填充 roles,AuthPrincipal 对下游零改动 - SecurityConfig:注入 RoleResolver 传给 JwtAuthFilter - platform-auth/pom.xml 加 Caffeine 依赖 - 单测覆盖:RoleResolverTest(命中/evict/evictAll/TTL降级)、JwtServiceTest 更新 (roles不入token断言 + token<1KB断言)、EngineContextIsolationTest/SecurityProfileTest 适配 实测:admin token 316B,ceshi token 344B(原6413/16924字符)
This commit is contained in:
@@ -22,6 +22,8 @@
|
|||||||
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId></dependency>
|
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId></dependency>
|
||||||
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><scope>runtime</scope></dependency>
|
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><scope>runtime</scope></dependency>
|
||||||
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId><scope>runtime</scope></dependency>
|
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId><scope>runtime</scope></dependency>
|
||||||
|
<!-- F2-6 JWT 瘦身:RoleResolver 服务端解析角色,Caffeine 缓存 userId→roles(TTL 5 分钟) -->
|
||||||
|
<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId></dependency>
|
||||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
|
||||||
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency>
|
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|||||||
@@ -36,9 +36,11 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
|||||||
private static final String PREFIX = "Bearer ";
|
private static final String PREFIX = "Bearer ";
|
||||||
|
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
|
private final RoleResolver roleResolver;
|
||||||
|
|
||||||
public JwtAuthFilter(JwtService jwtService) {
|
public JwtAuthFilter(JwtService jwtService, RoleResolver roleResolver) {
|
||||||
this.jwtService = jwtService;
|
this.jwtService = jwtService;
|
||||||
|
this.roleResolver = roleResolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -62,7 +64,12 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 解析 Bearer 令牌;无头/格式不符/校验失败均返回 null(不认证)。 */
|
/**
|
||||||
|
* 解析 Bearer 令牌;无头/格式不符/校验失败均返回 null(不认证)。
|
||||||
|
*
|
||||||
|
* <p>F2-6 JWT 瘦身:token parse 后 roles 为空列表,此处调 {@link RoleResolver}
|
||||||
|
* 按 userId 查角色(Caffeine 缓存 TTL 5 分钟),重新构造含角色的 {@link AuthPrincipal}。
|
||||||
|
*/
|
||||||
private AuthPrincipal resolve(HttpServletRequest request) {
|
private AuthPrincipal resolve(HttpServletRequest request) {
|
||||||
String header = request.getHeader(HEADER);
|
String header = request.getHeader(HEADER);
|
||||||
if (header == null || !header.startsWith(PREFIX)) {
|
if (header == null || !header.startsWith(PREFIX)) {
|
||||||
@@ -73,7 +80,12 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return jwtService.parse(token);
|
AuthPrincipal slim = jwtService.parse(token);
|
||||||
|
// F2-6:服务端解析角色,填充进新的 AuthPrincipal
|
||||||
|
List<String> roles = roleResolver.resolve(slim.userId());
|
||||||
|
return new AuthPrincipal(
|
||||||
|
slim.userId(), slim.account(), slim.name(),
|
||||||
|
slim.depart(), slim.org(), roles);
|
||||||
} catch (JwtException | IllegalArgumentException e) {
|
} catch (JwtException | IllegalArgumentException e) {
|
||||||
// 伪造/过期/篡改:记日志(不含令牌明文),不认证 → 受保护路径将得 401
|
// 伪造/过期/篡改:记日志(不含令牌明文),不认证 → 受保护路径将得 401
|
||||||
log.debug("JWT 校验失败,拒绝认证: {}", e.getMessage());
|
log.debug("JWT 校验失败,拒绝认证: {}", e.getMessage());
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ public class JwtService {
|
|||||||
static final String CLAIM_NAME = "name";
|
static final String CLAIM_NAME = "name";
|
||||||
static final String CLAIM_DEPART = "depart";
|
static final String CLAIM_DEPART = "depart";
|
||||||
static final String CLAIM_ORG = "org";
|
static final String CLAIM_ORG = "org";
|
||||||
static final String CLAIM_ROLES = "roles";
|
// F2-6 JWT 瘦身:roles 不再入 claims,服务端按 userId 解析(RoleResolver)
|
||||||
|
|
||||||
private final SecretKey key;
|
private final SecretKey key;
|
||||||
private final long expireSeconds;
|
private final long expireSeconds;
|
||||||
@@ -58,7 +58,12 @@ public class JwtService {
|
|||||||
this.issuer = props.getIssuer();
|
this.issuer = props.getIssuer();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 为已通过密码校验的用户签发访问令牌。 */
|
/**
|
||||||
|
* 为已通过密码校验的用户签发访问令牌。
|
||||||
|
*
|
||||||
|
* <p>F2-6 JWT 瘦身:roles 不入 claims,token 仅携带 userId/account/name/depart/org。
|
||||||
|
* 服务端每次请求由 {@link RoleResolver} 按 userId 解析角色(Caffeine 缓存 TTL 5 分钟)。
|
||||||
|
*/
|
||||||
public String issue(AuthPrincipal principal) {
|
public String issue(AuthPrincipal principal) {
|
||||||
Instant now = Instant.now();
|
Instant now = Instant.now();
|
||||||
Instant exp = now.plusSeconds(expireSeconds);
|
Instant exp = now.plusSeconds(expireSeconds);
|
||||||
@@ -70,7 +75,7 @@ public class JwtService {
|
|||||||
.claim(CLAIM_NAME, principal.name())
|
.claim(CLAIM_NAME, principal.name())
|
||||||
.claim(CLAIM_DEPART, principal.depart())
|
.claim(CLAIM_DEPART, principal.depart())
|
||||||
.claim(CLAIM_ORG, principal.org())
|
.claim(CLAIM_ORG, principal.org())
|
||||||
.claim(CLAIM_ROLES, principal.roles())
|
// F2-6:roles 故意不写入 token,服务端解析
|
||||||
.issuedAt(Date.from(now))
|
.issuedAt(Date.from(now))
|
||||||
.expiration(Date.from(exp))
|
.expiration(Date.from(exp))
|
||||||
.signWith(key)
|
.signWith(key)
|
||||||
@@ -81,7 +86,10 @@ public class JwtService {
|
|||||||
* 校验并解析令牌。签名错误/过期/issuer 不符/格式非法均抛 {@link JwtException}
|
* 校验并解析令牌。签名错误/过期/issuer 不符/格式非法均抛 {@link JwtException}
|
||||||
* (由调用方 {@code JwtAuthFilter} 翻译为 401,绝不放行)。
|
* (由调用方 {@code JwtAuthFilter} 翻译为 401,绝不放行)。
|
||||||
*
|
*
|
||||||
* @return 令牌内嵌的用户主体
|
* <p>F2-6 JWT 瘦身:token 中不含 roles,此处 roles 固定返回空列表;
|
||||||
|
* 调用方 {@link JwtAuthFilter} 负责调 {@link RoleResolver} 填充真实角色。
|
||||||
|
*
|
||||||
|
* @return 令牌内嵌的用户主体(roles 为空列表,待 RoleResolver 填充)
|
||||||
* @throws JwtException 校验失败
|
* @throws JwtException 校验失败
|
||||||
*/
|
*/
|
||||||
public AuthPrincipal parse(String token) {
|
public AuthPrincipal parse(String token) {
|
||||||
@@ -97,7 +105,7 @@ public class JwtService {
|
|||||||
claims.get(CLAIM_NAME, String.class),
|
claims.get(CLAIM_NAME, String.class),
|
||||||
claims.get(CLAIM_DEPART, String.class),
|
claims.get(CLAIM_DEPART, String.class),
|
||||||
claims.get(CLAIM_ORG, String.class),
|
claims.get(CLAIM_ORG, String.class),
|
||||||
rolesOf(claims));
|
List.of()); // F2-6:roles 由 RoleResolver 服务端解析,不从 token 读
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 令牌有效期(秒),登录响应回带供前端管理刷新时机。 */
|
/** 令牌有效期(秒),登录响应回带供前端管理刷新时机。 */
|
||||||
@@ -105,12 +113,5 @@ public class JwtService {
|
|||||||
return expireSeconds;
|
return expireSeconds;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private static List<String> rolesOf(Claims claims) {
|
|
||||||
Object raw = claims.get(CLAIM_ROLES);
|
|
||||||
if (raw instanceof List<?> list) {
|
|
||||||
return list.stream().map(String::valueOf).toList();
|
|
||||||
}
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package com.eip4.platform.auth.security;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
|
import org.springframework.jdbc.core.JdbcOperations;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* F2-6 JWT 瘦身:服务端角色解析器。
|
||||||
|
*
|
||||||
|
* <p>JWT 不再携带 roles,每次请求由本类按 userId 查角色并缓存。
|
||||||
|
* SQL 与 {@link SysUserService} 的 SQL_ROLES_BY_USER 同源:
|
||||||
|
* {@code sys_usergrouprole ⋈ sys_usergroupuser}(用户→用户组→角色)。
|
||||||
|
*
|
||||||
|
* <p><b>缓存策略</b>:Caffeine 本地缓存,TTL 5 分钟({@code expireAfterWrite}),
|
||||||
|
* 容量上限 5000 条(单客户用户规模上限)。
|
||||||
|
* 失效钩子:{@link AdminWriteController} 的用户组/角色变更端点调 {@link #evict} 或
|
||||||
|
* {@link #evictAll}(变更低频,不需精确失效时 evictAll 即可,5 分钟内自然 TTL 兜底)。
|
||||||
|
*
|
||||||
|
* <p>角色表不可达(org 表未移植等)时降级为空列表,不阻断请求。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class RoleResolver {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RoleResolver.class);
|
||||||
|
|
||||||
|
/** 角色解析 SQL:与 SysUserService.SQL_ROLES_BY_USER 同源。 */
|
||||||
|
private static final String SQL =
|
||||||
|
"SELECT DISTINCT ugr.roleid FROM sys_usergrouprole ugr "
|
||||||
|
+ "INNER JOIN sys_usergroupuser ugu ON ugu.usergroupid = ugr.usergroupid "
|
||||||
|
+ "WHERE ugu.userid = ?";
|
||||||
|
|
||||||
|
/** userId → roles 缓存,TTL 5 分钟,容量 5000。 */
|
||||||
|
private final Cache<String, List<String>> cache = Caffeine.newBuilder()
|
||||||
|
.expireAfterWrite(5, TimeUnit.MINUTES)
|
||||||
|
.maximumSize(5_000)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
private final JdbcOperations jdbc;
|
||||||
|
|
||||||
|
public RoleResolver(JdbcOperations jdbc) {
|
||||||
|
this.jdbc = jdbc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按 userId 解析角色列表(先查缓存,未命中则查库并回填)。
|
||||||
|
*
|
||||||
|
* @param userId SYS_USER.SYS_USER_ID
|
||||||
|
* @return 角色 id 列表,永不为 null;角色表不可达时返回空列表
|
||||||
|
*/
|
||||||
|
public List<String> resolve(String userId) {
|
||||||
|
if (userId == null || userId.isBlank()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return cache.get(userId, this::loadFromDb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失效指定用户的角色缓存(用户组成员变更时调用)。
|
||||||
|
*
|
||||||
|
* @param userId SYS_USER.SYS_USER_ID
|
||||||
|
*/
|
||||||
|
public void evict(String userId) {
|
||||||
|
if (userId != null && !userId.isBlank()) {
|
||||||
|
cache.invalidate(userId.trim());
|
||||||
|
log.debug("[RoleResolver] evict userId={}", userId.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全量失效角色缓存(用户组角色关联变更时调用,影响面不可精确确定时使用)。
|
||||||
|
*/
|
||||||
|
public void evictAll() {
|
||||||
|
cache.invalidateAll();
|
||||||
|
log.debug("[RoleResolver] evictAll");
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> loadFromDb(String userId) {
|
||||||
|
try {
|
||||||
|
List<String> rows = jdbc.queryForList(SQL, String.class, userId);
|
||||||
|
List<String> result = new ArrayList<>(rows.size());
|
||||||
|
for (String r : rows) {
|
||||||
|
String t = r == null ? null : r.trim();
|
||||||
|
if (t != null && !t.isEmpty()) {
|
||||||
|
result.add(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
log.warn("[RoleResolver] 角色解析失败(org 表可能未移植),降级为空角色 userId={}: {}",
|
||||||
|
userId, e.getMessage());
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,9 +38,11 @@ public class SecurityConfig {
|
|||||||
};
|
};
|
||||||
|
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
|
private final RoleResolver roleResolver;
|
||||||
|
|
||||||
public SecurityConfig(JwtService jwtService) {
|
public SecurityConfig(JwtService jwtService, RoleResolver roleResolver) {
|
||||||
this.jwtService = jwtService;
|
this.jwtService = jwtService;
|
||||||
|
this.roleResolver = roleResolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 生产链:其余 /api/** 一律需认证,无测试旁路。 */
|
/** 生产链:其余 /api/** 一律需认证,无测试旁路。 */
|
||||||
@@ -87,7 +89,7 @@ public class SecurityConfig {
|
|||||||
.httpBasic(AbstractHttpConfigurer::disable)
|
.httpBasic(AbstractHttpConfigurer::disable)
|
||||||
.logout(AbstractHttpConfigurer::disable)
|
.logout(AbstractHttpConfigurer::disable)
|
||||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
.addFilterBefore(new JwtAuthFilter(jwtService),
|
.addFilterBefore(new JwtAuthFilter(jwtService, roleResolver),
|
||||||
UsernamePasswordAuthenticationFilter.class);
|
UsernamePasswordAuthenticationFilter.class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ package com.eip4.platform.auth.security;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
@@ -39,6 +42,19 @@ class EngineContextIsolationTest {
|
|||||||
return new JwtService(p);
|
return new JwtService(p);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* F2-6:测试辅助 — 构造 RoleResolver mock,按 userId 返回指定角色列表。
|
||||||
|
* userId→roles 映射由调用方提供;未在映射中的 userId 返回空列表。
|
||||||
|
*/
|
||||||
|
private static RoleResolver mockRoles(java.util.Map<String, List<String>> mapping) {
|
||||||
|
RoleResolver rr = mock(RoleResolver.class);
|
||||||
|
when(rr.resolve(anyString())).thenAnswer(inv -> {
|
||||||
|
String uid = inv.getArgument(0);
|
||||||
|
return mapping.getOrDefault(uid, List.of());
|
||||||
|
});
|
||||||
|
return rr;
|
||||||
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
void cleanup() {
|
void cleanup() {
|
||||||
UserSession.remove();
|
UserSession.remove();
|
||||||
@@ -67,7 +83,9 @@ class EngineContextIsolationTest {
|
|||||||
String token = svc.issue(new AuthPrincipal("USER_BOB", "bob", "鲍勃",
|
String token = svc.issue(new AuthPrincipal("USER_BOB", "bob", "鲍勃",
|
||||||
null, null, List.of("ROLE_TASK")));
|
null, null, List.of("ROLE_TASK")));
|
||||||
|
|
||||||
JwtAuthFilter filter = new JwtAuthFilter(svc);
|
// F2-6:RoleResolver mock,USER_BOB 返回 ROLE_TASK
|
||||||
|
RoleResolver rr = mockRoles(java.util.Map.of("USER_BOB", List.of("ROLE_TASK")));
|
||||||
|
JwtAuthFilter filter = new JwtAuthFilter(svc, rr);
|
||||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/entity/x/list");
|
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/entity/x/list");
|
||||||
req.addHeader("Authorization", "Bearer " + token);
|
req.addHeader("Authorization", "Bearer " + token);
|
||||||
MockHttpServletResponse resp = new MockHttpServletResponse();
|
MockHttpServletResponse resp = new MockHttpServletResponse();
|
||||||
@@ -91,7 +109,8 @@ class EngineContextIsolationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void 无令牌不填充上下文且收尾干净() throws Exception {
|
void 无令牌不填充上下文且收尾干净() throws Exception {
|
||||||
JwtAuthFilter filter = new JwtAuthFilter(jwtService());
|
RoleResolver rr = mockRoles(java.util.Map.of());
|
||||||
|
JwtAuthFilter filter = new JwtAuthFilter(jwtService(), rr);
|
||||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/entity/x/list");
|
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/entity/x/list");
|
||||||
MockHttpServletResponse resp = new MockHttpServletResponse();
|
MockHttpServletResponse resp = new MockHttpServletResponse();
|
||||||
AtomicBoolean emptyInChain = new AtomicBoolean(false);
|
AtomicBoolean emptyInChain = new AtomicBoolean(false);
|
||||||
@@ -110,22 +129,33 @@ class EngineContextIsolationTest {
|
|||||||
@Test
|
@Test
|
||||||
void 并发不同令牌各自隔离不串号() throws Exception {
|
void 并发不同令牌各自隔离不串号() throws Exception {
|
||||||
JwtService svc = jwtService();
|
JwtService svc = jwtService();
|
||||||
JwtAuthFilter filter = new JwtAuthFilter(svc);
|
|
||||||
|
|
||||||
int threads = 16;
|
int threads = 16;
|
||||||
int iterations = 200;
|
int iterations = 200;
|
||||||
|
|
||||||
|
// F2-6:为每个 userId 构建 RoleResolver mock(并发安全:mock 不含可变状态)
|
||||||
|
java.util.Map<String, List<String>> roleMap = new java.util.HashMap<>();
|
||||||
|
java.util.Map<String, String> tokenMap = new java.util.HashMap<>();
|
||||||
|
for (int i = 0; i < threads; i++) {
|
||||||
|
String userId = "USER_" + i;
|
||||||
|
String role = "ROLE_" + i;
|
||||||
|
roleMap.put(userId, List.of(role));
|
||||||
|
tokenMap.put(userId, svc.issue(new AuthPrincipal(userId, "acc" + i, "n" + i,
|
||||||
|
null, null, List.of(role))));
|
||||||
|
}
|
||||||
|
RoleResolver rr = mockRoles(roleMap);
|
||||||
|
JwtAuthFilter filter = new JwtAuthFilter(svc, rr);
|
||||||
|
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||||
CountDownLatch start = new CountDownLatch(1);
|
CountDownLatch start = new CountDownLatch(1);
|
||||||
CountDownLatch done = new CountDownLatch(threads);
|
CountDownLatch done = new CountDownLatch(threads);
|
||||||
// 收集任何串号:key=期望 userId,value=实际观测到的不一致 userId
|
// 收集任何串号:key=期望 userId,value=实际观测到的不一致 userId
|
||||||
ConcurrentHashMap<String, String> leaks = new ConcurrentHashMap<>();
|
ConcurrentHashMap<String, String> leaks = new ConcurrentHashMap<>();
|
||||||
AtomicBoolean residueAfter = new AtomicBoolean(false);
|
AtomicBoolean residueAfter = new AtomicBoolean(false);
|
||||||
|
|
||||||
for (int i = 0; i < threads; i++) {
|
for (int i = 0; i < threads; i++) {
|
||||||
String userId = "USER_" + i;
|
String userId = "USER_" + i;
|
||||||
String role = "ROLE_" + i;
|
String role = "ROLE_" + i;
|
||||||
String token = svc.issue(new AuthPrincipal(userId, "acc" + i, "n" + i,
|
String token = tokenMap.get(userId);
|
||||||
null, null, List.of(role)));
|
|
||||||
pool.submit(() -> {
|
pool.submit(() -> {
|
||||||
try {
|
try {
|
||||||
start.await();
|
start.await();
|
||||||
@@ -147,6 +177,7 @@ class EngineContextIsolationTest {
|
|||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
List<String> roles = ctx == null ? null
|
List<String> roles = ctx == null ? null
|
||||||
: (List<String>) ctx.get(LoggedInUser.ROLES);
|
: (List<String>) ctx.get(LoggedInUser.ROLES);
|
||||||
|
// F2-6:roles 由 RoleResolver mock 填充,期望与 roleMap 一致
|
||||||
if (roles == null || !roles.equals(List.of(role))) {
|
if (roles == null || !roles.equals(List.of(role))) {
|
||||||
leaks.put(userId + "#roles", String.valueOf(roles));
|
leaks.put(userId + "#roles", String.valueOf(roles));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ class JwtServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void 签发并回读全部claim() {
|
void 签发并回读基础claim_roles不入token() {
|
||||||
JwtService svc = service(3600);
|
JwtService svc = service(3600);
|
||||||
String token = svc.issue(sample());
|
String token = svc.issue(sample());
|
||||||
AuthPrincipal back = svc.parse(token);
|
AuthPrincipal back = svc.parse(token);
|
||||||
@@ -42,7 +42,16 @@ class JwtServiceTest {
|
|||||||
assertEquals("爱丽丝", back.name());
|
assertEquals("爱丽丝", back.name());
|
||||||
assertEquals("DEPT_A", back.depart());
|
assertEquals("DEPT_A", back.depart());
|
||||||
assertEquals("ORG_1", back.org());
|
assertEquals("ORG_1", back.org());
|
||||||
assertEquals(List.of("ROLE_CUSTOMER", "ROLE_TASK"), back.roles());
|
// F2-6 JWT 瘦身:roles 不入 token,parse 返回空列表,由 RoleResolver 服务端填充
|
||||||
|
assertEquals(List.of(), back.roles());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void token长度小于1KB() {
|
||||||
|
JwtService svc = service(3600);
|
||||||
|
// sample 有 2 个 roles;实际多角色用户(如 ceshi 有数百角色)瘦身后 token 应远小于 1KB
|
||||||
|
String token = svc.issue(sample());
|
||||||
|
assertTrue(token.length() < 1024, "token 长度应 <1KB,实际=" + token.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package com.eip4.platform.auth.security;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.jdbc.core.JdbcOperations;
|
||||||
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RoleResolver 单测(mock JdbcOperations,不起 Spring 上下文)。
|
||||||
|
*
|
||||||
|
* <p>覆盖:缓存命中(同 userId 二次调用不再查库)、evict 失效(失效后重新查库)、
|
||||||
|
* evictAll 全量失效、数据库异常降级为空列表。
|
||||||
|
*/
|
||||||
|
class RoleResolverTest {
|
||||||
|
|
||||||
|
private JdbcOperations jdbc;
|
||||||
|
private RoleResolver resolver;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
jdbc = mock(JdbcOperations.class);
|
||||||
|
resolver = new RoleResolver(jdbc);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 首次查库并返回角色列表() {
|
||||||
|
when(jdbc.queryForList(any(String.class), eq(String.class), eq("USER_1")))
|
||||||
|
.thenReturn(List.of("ROLE_A", "ROLE_B"));
|
||||||
|
|
||||||
|
List<String> roles = resolver.resolve("USER_1");
|
||||||
|
|
||||||
|
assertEquals(List.of("ROLE_A", "ROLE_B"), roles);
|
||||||
|
verify(jdbc, times(1)).queryForList(any(String.class), eq(String.class), eq("USER_1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 缓存命中_第二次不查库() {
|
||||||
|
when(jdbc.queryForList(any(String.class), eq(String.class), eq("USER_1")))
|
||||||
|
.thenReturn(List.of("ROLE_A"));
|
||||||
|
|
||||||
|
resolver.resolve("USER_1");
|
||||||
|
resolver.resolve("USER_1"); // 第二次应命中缓存
|
||||||
|
|
||||||
|
// 只查一次库
|
||||||
|
verify(jdbc, times(1)).queryForList(any(String.class), eq(String.class), eq("USER_1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void evict后重新查库() {
|
||||||
|
when(jdbc.queryForList(any(String.class), eq(String.class), eq("USER_1")))
|
||||||
|
.thenReturn(List.of("ROLE_A"))
|
||||||
|
.thenReturn(List.of("ROLE_A", "ROLE_NEW")); // 第二次查库返回新角色
|
||||||
|
|
||||||
|
resolver.resolve("USER_1"); // 第一次:查库,缓存
|
||||||
|
resolver.evict("USER_1"); // 失效
|
||||||
|
List<String> after = resolver.resolve("USER_1"); // 第二次:重新查库
|
||||||
|
|
||||||
|
verify(jdbc, times(2)).queryForList(any(String.class), eq(String.class), eq("USER_1"));
|
||||||
|
assertEquals(List.of("ROLE_A", "ROLE_NEW"), after);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void evictAll后所有用户重新查库() {
|
||||||
|
when(jdbc.queryForList(any(String.class), eq(String.class), eq("USER_1")))
|
||||||
|
.thenReturn(List.of("ROLE_A"));
|
||||||
|
when(jdbc.queryForList(any(String.class), eq(String.class), eq("USER_2")))
|
||||||
|
.thenReturn(List.of("ROLE_B"));
|
||||||
|
|
||||||
|
resolver.resolve("USER_1");
|
||||||
|
resolver.resolve("USER_2");
|
||||||
|
resolver.evictAll();
|
||||||
|
resolver.resolve("USER_1");
|
||||||
|
resolver.resolve("USER_2");
|
||||||
|
|
||||||
|
verify(jdbc, times(2)).queryForList(any(String.class), eq(String.class), eq("USER_1"));
|
||||||
|
verify(jdbc, times(2)).queryForList(any(String.class), eq(String.class), eq("USER_2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 数据库异常降级为空列表() {
|
||||||
|
when(jdbc.queryForList(any(String.class), eq(String.class), eq("USER_ERR")))
|
||||||
|
.thenThrow(new org.springframework.dao.DataAccessResourceFailureException("连接失败"));
|
||||||
|
|
||||||
|
List<String> roles = resolver.resolve("USER_ERR");
|
||||||
|
|
||||||
|
assertTrue(roles.isEmpty(), "DB 异常时应降级为空列表");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void userId为null或空白返回空列表() {
|
||||||
|
assertTrue(resolver.resolve(null).isEmpty());
|
||||||
|
assertTrue(resolver.resolve(" ").isEmpty());
|
||||||
|
// 不应查库
|
||||||
|
verify(jdbc, times(0)).queryForList(any(String.class), eq(String.class), any());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
package com.eip4.platform.auth.security;
|
package com.eip4.platform.auth.security;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||||
@@ -31,11 +36,15 @@ class SecurityProfileTest {
|
|||||||
props.setSecret(SECRET);
|
props.setSecret(SECRET);
|
||||||
props.setIssuer("eip4-platform");
|
props.setIssuer("eip4-platform");
|
||||||
JwtService jwt = new JwtService(props);
|
JwtService jwt = new JwtService(props);
|
||||||
|
// F2-6:SecurityConfig 现在依赖 RoleResolver,测试上下文注册 mock 即可
|
||||||
|
RoleResolver roleResolver = mock(RoleResolver.class);
|
||||||
|
when(roleResolver.resolve(anyString())).thenReturn(List.of());
|
||||||
return new WebApplicationContextRunner()
|
return new WebApplicationContextRunner()
|
||||||
.withConfiguration(org.springframework.boot.autoconfigure.AutoConfigurations.of(
|
.withConfiguration(org.springframework.boot.autoconfigure.AutoConfigurations.of(
|
||||||
SecurityAutoConfiguration.class,
|
SecurityAutoConfiguration.class,
|
||||||
SecurityFilterAutoConfiguration.class))
|
SecurityFilterAutoConfiguration.class))
|
||||||
.withBean(JwtService.class, () -> jwt)
|
.withBean(JwtService.class, () -> jwt)
|
||||||
|
.withBean(RoleResolver.class, () -> roleResolver)
|
||||||
.withUserConfiguration(SecurityConfig.class);
|
.withUserConfiguration(SecurityConfig.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user