feat(auth): P2-2 Spring Security 无状态 JWT 认证链路 + UserSession 引擎上下文适配

- jjwt 0.12.6 HS256;密钥配置化(EIP4_AUTH_JWT_SECRET),启动期强度校验,不入仓库
- 密码兼容:复刻 framework EncryptUtil 无盐 MD5 + 常量时间比对(侦察证据见报告)
- JwtAuthFilter:SecurityContext + 引擎 UserSession(静态 ThreadLocal)请求级 set/finally clear,16线程×200次并发隔离单测
- SecurityConfig 双链:prod 严格 401 / 非 prod 保留对拍测试通道(单测断言生产关闭)
- EntityController.buildCtx 三级优先(asUser > JWT > ADMIN),修复 JWT ctx 被 ADMIN 默认覆盖
- 实测:登录签发/过滤 16 行与 DB 吻合/伪造过期全 401;ci.sh 全绿;手册新增 §5.29-5.31

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 13:37:34 +08:00
parent 19dcd74f9d
commit 33d793b825
21 changed files with 1453 additions and 14 deletions

View File

@@ -0,0 +1,14 @@
package com.eip4.platform.auth.security;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* platform-auth 安全模块装配入口:注册 {@link JwtProperties}。
* 其余组件({@link JwtService}/{@link SysUserService}/{@link SecurityConfig}/
* {@link AuthController})由 {@code com.eip4.platform} 组件扫描自动拾取。
*/
@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class AuthConfig {
}

View File

@@ -0,0 +1,71 @@
package com.eip4.platform.auth.security;
import java.util.Optional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 认证端点。{@code /api/auth/**} 由 {@code SecurityConfig} 放行(登录本身无需令牌)。
*/
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final SysUserService sysUserService;
private final JwtService jwtService;
public AuthController(SysUserService sysUserService, JwtService jwtService) {
this.sysUserService = sysUserService;
this.jwtService = jwtService;
}
/**
* 账号口令登录,成功签发 JWT。
*
* <p>失败统一返回 401 + 含糊文案(不区分「账号不存在」与「口令错误」,避免账号枚举)。
*/
@PostMapping("/login")
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest req) {
if (req == null || req.account() == null || req.password() == null) {
return ResponseEntity.status(401).body(LoginResponse.failure("账号或密码错误"));
}
Optional<AuthPrincipal> user = sysUserService.authenticate(req.account(), req.password());
if (user.isEmpty()) {
return ResponseEntity.status(401).body(LoginResponse.failure("账号或密码错误"));
}
AuthPrincipal p = user.get();
String token = jwtService.issue(p);
return ResponseEntity.ok(LoginResponse.success(
token, jwtService.getExpireSeconds(), p.userId(), p.account(), p.name(), p.roles()));
}
/** 登录请求体。 */
public record LoginRequest(String account, String password) {
}
/** 登录响应体(失败时仅含 success=false + msg)。 */
public record LoginResponse(
boolean success,
String msg,
String token,
Long expireSeconds,
String userId,
String account,
String name,
java.util.List<String> roles) {
static LoginResponse success(String token, long expireSeconds,
String userId, String account, String name,
java.util.List<String> roles) {
return new LoginResponse(true, "", token, expireSeconds, userId, account, name, roles);
}
static LoginResponse failure(String msg) {
return new LoginResponse(false, msg, null, null, null, null, null, null);
}
}
}

View File

@@ -0,0 +1,36 @@
package com.eip4.platform.auth.security;
import java.util.List;
/**
* 已认证用户主体:JWT claims 的不可变载体。
*
* <p>同时承担两个角色:(1) 作为 Spring Security 的 principal;(2) 作为引擎上下文
* {@code UserSession} 的数据来源。各字段直接映射 {@code SYS_USER} 的列与
* {@code LoggedInUser} 契约:
* <ul>
* <li>{@code userId} → {@code CURRENTUSER}({@code SYS_USER_ID},行级过滤的 {@code CREATEBY={CURRENTUSERID}} 主体)</li>
* <li>{@code depart} → {@code CURRENTDEPART}({@code MASTERDEPART})</li>
* <li>{@code org} → {@code CURRENTORG}({@code USERORGID})</li>
* <li>{@code roles} → {@code ROLES}(List,驱动 {@code SYS_FILTERRULE} 角色匹配)</li>
* </ul>
*
* @param userId 用户主键 SYS_USER_ID(引擎 CURRENTUSER)
* @param account 登录账号 ACCOUNT
* @param name 姓名 NAME(展示用)
* @param depart 主部门 MASTERDEPART(引擎 CURRENTDEPART,可空)
* @param org 所属机构 USERORGID(引擎 CURRENTORG,可空)
* @param roles 角色 id 列表(引擎 ROLES,永不为 null)
*/
public record AuthPrincipal(
String userId,
String account,
String name,
String depart,
String org,
List<String> roles) {
public AuthPrincipal {
roles = roles == null ? List.of() : List.copyOf(roles);
}
}

View File

@@ -0,0 +1,53 @@
package com.eip4.platform.auth.security;
import java.util.List;
import java.util.Properties;
import com.dsasp.server.common.user.service.LoggedInUser;
import com.dsasp.server.common.util.UserSession;
/**
* 引擎上下文桥:把 {@link AuthPrincipal} 写入保真层引擎的请求级上下文 {@code UserSession}。
*
* <p>{@code UserSession} 是<strong>静态 ThreadLocal&lt;Properties&gt;</strong>(读源码核实):
* 引擎全程从当前线程取 {@code CURRENTUSER/CURRENTDEPART/CURRENTORG} 与
* {@code ROLES}(List)。因此每请求必须在<em>当前处理线程</em>上 {@code set},
* 处理结束 <strong>无条件 {@code clear}</strong>(finally),否则线程被 Tomcat 复用时
* 会把上一请求的身份泄漏给下一请求。本类只做 set/clear,泄漏隔离由
* {@code JwtAuthFilter} 的 try/finally 保证,并由并发单测断言。
*
* <p>不改保真层一行:仅调用 {@code UserSession.set/remove} 公有静态法。
*/
public final class EngineContextBinder {
private EngineContextBinder() {
}
/**
* 用已认证主体覆盖当前线程的引擎上下文。
*
* <p>非 ADMIN 上下文(CURRENTUSER = 真实 userId)将触发引擎行级数据过滤
* (引擎仅当 {@code CURRENTUSER != ADMIN} 时调 {@code dataPrivilegeService}),
* 从而以 JWT 内的 userId/roles 替代 C2 的 asUser/roles 测试参数。
*/
public static void bind(AuthPrincipal principal) {
Properties ctx = new Properties();
if (principal.userId() != null) {
ctx.setProperty(LoggedInUser.CURRENTUSER, principal.userId());
}
if (principal.depart() != null) {
ctx.setProperty(LoggedInUser.CURRENTDEPART, principal.depart());
}
if (principal.org() != null) {
ctx.setProperty(LoggedInUser.CURRENTORG, principal.org());
}
// ROLES 是 List(非字符串):引擎按 ctx.get("ROLES") 强转 List<String>,故用 put 而非 setProperty
ctx.put(LoggedInUser.ROLES, List.copyOf(principal.roles()));
UserSession.set(ctx);
}
/** 清空当前线程的引擎上下文(请求收尾,防跨请求泄漏)。 */
public static void clear() {
UserSession.remove();
}
}

View File

@@ -0,0 +1,93 @@
package com.eip4.platform.auth.security;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* JWT 认证过滤器:校验 {@code Authorization: Bearer <token>},通过则
* (1) 构造 Spring Security 的 {@code SecurityContext};
* (2) 把 claims 填充进引擎 {@code UserSession}(经 {@link EngineContextBinder})。
*
* <p><strong>跨请求隔离</strong>:引擎上下文在 {@code finally} 中无条件
* {@code clear},确保 Tomcat 复用工作线程时绝不泄漏上一请求身份。
*
* <p><strong>失败即不放行</strong>:令牌缺失/签名错/过期/伪造时,本过滤器不设置
* Authentication,把请求原样下放——受保护路径由 {@code SecurityConfig} 的
* {@code authenticated()} 规则拒为 401(放行路径如 /api/auth/** 不受影响)。
* 绝不因解析异常而「兜底放行」。
*/
public class JwtAuthFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(JwtAuthFilter.class);
private static final String HEADER = "Authorization";
private static final String PREFIX = "Bearer ";
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
boolean ctxBound = false;
try {
AuthPrincipal principal = resolve(request);
if (principal != null) {
authenticate(principal);
EngineContextBinder.bind(principal);
ctxBound = true;
}
chain.doFilter(request, response);
} finally {
// 无条件清理:即便下游抛异常,也必须把引擎上下文从复用线程上摘除
if (ctxBound) {
EngineContextBinder.clear();
}
}
}
/** 解析 Bearer 令牌;无头/格式不符/校验失败均返回 null(不认证)。 */
private AuthPrincipal resolve(HttpServletRequest request) {
String header = request.getHeader(HEADER);
if (header == null || !header.startsWith(PREFIX)) {
return null;
}
String token = header.substring(PREFIX.length()).trim();
if (token.isEmpty()) {
return null;
}
try {
return jwtService.parse(token);
} catch (JwtException | IllegalArgumentException e) {
// 伪造/过期/篡改:记日志(不含令牌明文),不认证 → 受保护路径将得 401
log.debug("JWT 校验失败,拒绝认证: {}", e.getMessage());
return null;
}
}
/** 把已校验主体写入 SecurityContext,roles → ROLE_ 权限。 */
private void authenticate(AuthPrincipal principal) {
List<SimpleGrantedAuthority> authorities = principal.roles().stream()
.map(r -> new SimpleGrantedAuthority("ROLE_" + r))
.toList();
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(principal, null, authorities);
SecurityContextHolder.getContext().setAuthentication(auth);
}
}

View File

@@ -0,0 +1,48 @@
package com.eip4.platform.auth.security;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* JWT 配置(前缀 {@code eip4.auth.jwt})。
*
* <p>密钥<strong>不硬编码进仓库</strong>:本地默认值仅放 {@code application-local.yml}
* (HS256 至少 256 bit 的占位密钥,注明生产须替换);生产经环境变量
* {@code EIP4_AUTH_JWT_SECRET} 或外部配置注入。本类不内置任何默认密钥,
* 缺省时由 {@link JwtService} 启动期校验并报错,避免「忘了配密钥也能跑」的隐患。
*/
@ConfigurationProperties(prefix = "eip4.auth.jwt")
public class JwtProperties {
/** HS256 对称密钥(Base64 或原文均可,长度须 ≥32 字节)。无默认值,必须外部配置。 */
private String secret;
/** 访问令牌有效期(秒)。默认 8 小时。 */
private long expireSeconds = 8 * 60 * 60;
/** 令牌签发者标识,写入 iss claim 并在校验时比对。 */
private String issuer = "eip4-platform";
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public long getExpireSeconds() {
return expireSeconds;
}
public void setExpireSeconds(long expireSeconds) {
this.expireSeconds = expireSeconds;
}
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
}

View File

@@ -0,0 +1,116 @@
package com.eip4.platform.auth.security;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import javax.crypto.SecretKey;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
/**
* JWT 签发与校验(HS256 对称密钥,jjwt 0.12.x)。
*
* <p><strong>选型理由</strong>:无状态 JWT 是单体私有化部署的自然选择(免 session 共享)。
* 在 jjwt 与 spring-security-oauth2-jose 之间选 <em>jjwt</em>:本系统是<em>自签自验</em>的
* 单一签发方,不与外部 IdP 联邦、无需 JWKS/非对称轮转,HS256 + 配置化对称密钥即足够;
* oauth2-jose/资源服务器栈面向 OAuth2 联邦场景,在此属过度设计。jjwt API 精简、
* 0.12.x 强制安全默认(密钥长度校验、算法绑定),契合「最小可用」。
*
* <p>密钥来自 {@link JwtProperties#getSecret()},构造期即校验存在且长度达标
* (HS256 要求 ≥256 bit),缺失/过短直接启动失败——杜绝弱密钥裸奔。
*/
@Service
public class JwtService {
/** 自定义 claim 键(标准键 sub/iss/iat/exp 由 jjwt 内建)。 */
static final String CLAIM_USER_ID = "userId";
static final String CLAIM_ACCOUNT = "account";
static final String CLAIM_NAME = "name";
static final String CLAIM_DEPART = "depart";
static final String CLAIM_ORG = "org";
static final String CLAIM_ROLES = "roles";
private final SecretKey key;
private final long expireSeconds;
private final String issuer;
public JwtService(JwtProperties props) {
String secret = props.getSecret();
if (secret == null || secret.isBlank()) {
throw new IllegalStateException(
"JWT 密钥未配置:请设置 eip4.auth.jwt.secret(环境变量 EIP4_AUTH_JWT_SECRET)。"
+ "本地默认值见 application-local.yml,生产须替换为强随机密钥。");
}
byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
if (keyBytes.length < 32) {
throw new IllegalStateException(
"JWT 密钥过短:HS256 要求 ≥32 字节(256 bit),当前 " + keyBytes.length + " 字节。");
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.expireSeconds = props.getExpireSeconds();
this.issuer = props.getIssuer();
}
/** 为已通过密码校验的用户签发访问令牌。 */
public String issue(AuthPrincipal principal) {
Instant now = Instant.now();
Instant exp = now.plusSeconds(expireSeconds);
return Jwts.builder()
.issuer(issuer)
.subject(principal.account())
.claim(CLAIM_USER_ID, principal.userId())
.claim(CLAIM_ACCOUNT, principal.account())
.claim(CLAIM_NAME, principal.name())
.claim(CLAIM_DEPART, principal.depart())
.claim(CLAIM_ORG, principal.org())
.claim(CLAIM_ROLES, principal.roles())
.issuedAt(Date.from(now))
.expiration(Date.from(exp))
.signWith(key)
.compact();
}
/**
* 校验并解析令牌。签名错误/过期/issuer 不符/格式非法均抛 {@link JwtException}
* (由调用方 {@code JwtAuthFilter} 翻译为 401,绝不放行)。
*
* @return 令牌内嵌的用户主体
* @throws JwtException 校验失败
*/
public AuthPrincipal parse(String token) {
Claims claims = Jwts.parser()
.requireIssuer(issuer)
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload();
return new AuthPrincipal(
claims.get(CLAIM_USER_ID, String.class),
claims.get(CLAIM_ACCOUNT, String.class),
claims.get(CLAIM_NAME, String.class),
claims.get(CLAIM_DEPART, String.class),
claims.get(CLAIM_ORG, String.class),
rolesOf(claims));
}
/** 令牌有效期(秒),登录响应回带供前端管理刷新时机。 */
public long getExpireSeconds() {
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();
}
}

View File

@@ -0,0 +1,66 @@
package com.eip4.platform.auth.security;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 密码哈希——与保真层 {@code com.dsasp.server.common.util.EncryptUtil#encodeMD5String}
* <strong>逐字节一致</strong>的复刻(侦察结论见 P2认证实测报告.md §密码哈希)。
*
* <p>客户库 {@code SYS_USER.PASSWORD} 落地算法实况(读 framework 源码核实):
* <pre>
* MessageDigest.getInstance("MD5").digest(str.getBytes())
* → 逐字节小写十六进制(b<16 补前导 0),32 字符,<em>无盐、无迭代</em>。
* 登录比对为 hash.equals(PASSWORD) 纯字符串相等(见 AuthConstroller / ChangePasswordView)。
* </pre>
* 故本类不引入 Spring Security 的 {@code PasswordEncoder}(BCrypt 等),而原样复刻
* MD5——目标是<em>验证既有客户库口令</em>,保真兼容优先于「现代更强哈希」。
* (口令存储现代化是后续独立议题:可在改密路径渐进迁移,不在本认证任务范围。)
*
* <p><strong>不在保真层改一行</strong>:本复刻置于 {@code com.eip4},EncryptUtil 原样不动。
*/
public final class PasswordHasher {
private PasswordHasher() {
}
/**
* 计算明文口令的 MD5 哈希(小写十六进制,32 字符),与客户库存储格式一致。
*
* <p>实现与 EncryptUtil 一致:用平台默认字符集 {@code str.getBytes()}
* (与旧系统运行环境保持一致,避免跨字符集导致同口令异哈希)。
*/
public static String md5Hex(String plain) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(plain.getBytes());
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
int bt = b & 0xff;
if (bt < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(bt));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// MD5 是 JDK 必备算法,不可能缺失;包装为非受检异常以简化调用方
throw new IllegalStateException("JDK 缺少 MD5 算法", e);
}
}
/**
* 常量时间比对哈希,避免按字符早退的时序侧信道。
*
* @param storedHash 客户库 SYS_USER.PASSWORD 中的哈希
* @param plain 用户提交的明文口令
*/
public static boolean matches(String storedHash, String plain) {
if (storedHash == null || plain == null) {
return false;
}
byte[] a = storedHash.trim().getBytes();
byte[] b = md5Hex(plain).getBytes();
return MessageDigest.isEqual(a, b);
}
}

View File

@@ -0,0 +1,93 @@
package com.eip4.platform.auth.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
/**
* Spring Security 配置(无状态,STATELESS:不建 HttpSession,免 session 共享)。
*
* <p><strong>双链按 profile 装配</strong>:
* <ul>
* <li><b>prod</b>(生产):严格链——{@code /api/auth/**}、swagger/openapi 放行,
* 其余 {@code /api/**} 必须认证;<em>无任何测试旁路</em>。</li>
* <li><b>非 prod</b>(default/local/ci 等):宽松链——保留 {@code permitAll} 测试通道,
* 使对拍框架的免令牌 + {@code asUser/roles} 旁路可用(CI 依赖)。JWT 过滤器仍挂载,
* 带令牌照常填充引擎上下文。</li>
* </ul>
* 「生产绝不放行」由 {@code @Profile} 条件装配硬保证,并由 {@code SecurityProfileTest} 断言。
*
* <p>两链共享的放行清单与无状态/无表单/无 CSRF 设定抽到 {@link #applyCommon}。
*/
@Configuration
public class SecurityConfig {
/** 始终放行的路径:登录端点 + API 文档(认证前置依赖,不得拦)。 */
static final String[] PUBLIC_PATHS = {
"/api/auth/**",
"/swagger-ui/**", "/swagger-ui.html",
"/v3/api-docs/**", "/v3/api-docs.yaml",
};
private final JwtService jwtService;
public SecurityConfig(JwtService jwtService) {
this.jwtService = jwtService;
}
/** 生产链:其余 /api/** 一律需认证,无测试旁路。 */
@Bean
@Profile("prod")
SecurityFilterChain prodFilterChain(HttpSecurity http) throws Exception {
applyCommon(http);
http.authorizeHttpRequests(reg -> reg
.requestMatchers(publicMatchers()).permitAll()
.requestMatchers(new AntPathRequestMatcher("/api/**")).authenticated()
.anyRequest().authenticated());
// 未认证访问受保护资源返回 401(语义正确:凭据缺失/无效),而非 Spring 默认的 403
http.exceptionHandling(eh -> eh.authenticationEntryPoint(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)));
return http.build();
}
/**
* 非生产链(default/local/ci):保留 permitAll 测试通道。
* JWT 过滤器照常挂载——带令牌走 JWT 上下文,不带令牌走 asUser/roles 旁路(对拍 CI 依赖)。
*/
@Bean
@Profile("!prod")
SecurityFilterChain devFilterChain(HttpSecurity http) throws Exception {
applyCommon(http);
http.authorizeHttpRequests(reg -> reg.anyRequest().permitAll());
return http.build();
}
/** 放行清单转 Ant 路径匹配器(不依赖 MVC introspector,生产/切片测试一致)。 */
private static AntPathRequestMatcher[] publicMatchers() {
AntPathRequestMatcher[] matchers = new AntPathRequestMatcher[PUBLIC_PATHS.length];
for (int i = 0; i < PUBLIC_PATHS.length; i++) {
matchers[i] = new AntPathRequestMatcher(PUBLIC_PATHS[i]);
}
return matchers;
}
/** 共享:无状态会话、关表单/Basic/CSRF、挂 JWT 过滤器于用户名密码过滤器之前。 */
private void applyCommon(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.logout(AbstractHttpConfigurer::disable)
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtAuthFilter(jwtService),
UsernamePasswordAuthenticationFilter.class);
}
}

View File

@@ -0,0 +1,106 @@
package com.eip4.platform.auth.security;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 客户库 {@code SYS_USER} 账号口令校验 + 角色解析(只读 SELECT,不写库)。
*
* <p>口径与 framework 登录路径一致(见 {@code AuthConstroller#login} /
* {@code LoginWindow}):按 {@code ACCOUNT} 取用户行,口令存储为
* {@code EncryptUtil.encodeMD5String} 的小写十六进制 MD5,纯字符串相等比对(无盐)。
*
* <p>角色解析复刻 {@code RoleServiceImpl#findRolesByUserId}:
* {@code sys_usergrouprole ⋈ sys_usergroupuser}(用户→用户组→角色)。
* 较旧实现的字符串拼接,本处改用 {@code ?} 占位参数化(安全第 2 层「渐进参数化」)。
* org 模块尚未移植(P2-org 职责),故若用户组/角色表缺失则降级为空角色,不致登录失败。
*/
@Service
public class SysUserService {
private static final Logger log = LoggerFactory.getLogger(SysUserService.class);
/** SYS_USER 取用户:按账号查(参数化),仅取认证与上下文所需列。 */
private static final String SQL_FIND_BY_ACCOUNT =
"SELECT SYS_USER_ID, ACCOUNT, PASSWORD, NAME, MASTERDEPART, USERORGID "
+ "FROM SYS_USER WHERE ACCOUNT = ?";
/** 角色解析:用户→用户组→角色(参数化,复刻 RoleServiceImpl 的 join)。 */
private static final String SQL_ROLES_BY_USER =
"SELECT DISTINCT ugr.roleid FROM sys_usergrouprole ugr "
+ "INNER JOIN sys_usergroupuser ugu ON ugu.usergroupid = ugr.usergroupid "
+ "WHERE ugu.userid = ?";
private final JdbcTemplate jdbcTemplate;
public SysUserService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 校验账号口令,成功则返回填充好的用户主体(含角色)。
*
* @return 校验通过的 {@link AuthPrincipal};账号不存在或口令不符返回 {@link Optional#empty()}
*/
@Transactional(readOnly = true)
public Optional<AuthPrincipal> authenticate(String account, String rawPassword) {
if (account == null || account.isBlank() || rawPassword == null) {
return Optional.empty();
}
UserRow row;
try {
row = jdbcTemplate.queryForObject(SQL_FIND_BY_ACCOUNT, (rs, n) -> new UserRow(
trim(rs.getString("SYS_USER_ID")),
trim(rs.getString("ACCOUNT")),
rs.getString("PASSWORD"),
rs.getString("NAME"),
trim(rs.getString("MASTERDEPART")),
trim(rs.getString("USERORGID"))), account);
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
if (row == null || !PasswordHasher.matches(row.password(), rawPassword)) {
return Optional.empty();
}
List<String> roles = findRoles(row.userId());
return Optional.of(new AuthPrincipal(
row.userId(), row.account(), row.name(), row.depart(), row.org(), roles));
}
/** 解析用户角色;org 表缺失时降级为空列表(不阻断登录)。 */
private List<String> findRoles(String userId) {
try {
List<String> roles = jdbcTemplate.queryForList(SQL_ROLES_BY_USER, String.class, userId);
List<String> trimmed = new ArrayList<>(roles.size());
for (String r : roles) {
String t = trim(r);
if (t != null && !t.isEmpty()) {
trimmed.add(t);
}
}
return trimmed;
} catch (DataAccessException e) {
log.warn("角色解析失败(org 用户组/角色表可能尚未移植),登录降级为空角色: {}", e.getMessage());
return List.of();
}
}
private static String trim(String s) {
return s == null ? null : s.trim();
}
/** SYS_USER 行投影。char(36) 列 PG 返回带尾空格,统一 trim。 */
private record UserRow(
String userId, String account, String password,
String name, String depart, String org) {
}
}

View File

@@ -0,0 +1,175 @@
package com.eip4.platform.auth.security;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import com.dsasp.server.common.user.service.LoggedInUser;
import com.dsasp.server.common.util.UserSession;
/**
* 引擎上下文 set/clear 的<strong>并发隔离</strong>证明:
* (1) bind 后引擎 UserSession 命中正确身份;(2) clear/过滤器收尾后线程上无残留;
* (3) 多线程并发各自带不同令牌时,绝不串号(每线程只看到自己的 userId/roles)。
*/
class EngineContextIsolationTest {
private static final String SECRET = "isolation-test-secret-key-long-enough-abcdefghijklmnop";
private JwtService jwtService() {
JwtProperties p = new JwtProperties();
p.setSecret(SECRET);
p.setIssuer("eip4-platform");
return new JwtService(p);
}
@AfterEach
void cleanup() {
UserSession.remove();
SecurityContextHolder.clearContext();
}
@Test
void bind写入再clear清空() {
AuthPrincipal alice = new AuthPrincipal("USER_ALICE", "alice", "爱丽丝",
"DEPT_A", "ORG_1", List.of("ROLE_CUSTOMER"));
EngineContextBinder.bind(alice);
Properties ctx = UserSession.get();
assertEquals("USER_ALICE", ctx.getProperty(LoggedInUser.CURRENTUSER));
assertEquals("DEPT_A", ctx.getProperty(LoggedInUser.CURRENTDEPART));
assertEquals("ORG_1", ctx.getProperty(LoggedInUser.CURRENTORG));
assertEquals(List.of("ROLE_CUSTOMER"), ctx.get(LoggedInUser.ROLES));
EngineContextBinder.clear();
assertNull(UserSession.get(), "clear 后引擎上下文必须为空,杜绝跨请求泄漏");
}
@Test
void 过滤器请求收尾后清空上下文() throws Exception {
JwtService svc = jwtService();
String token = svc.issue(new AuthPrincipal("USER_BOB", "bob", "鲍勃",
null, null, List.of("ROLE_TASK")));
JwtAuthFilter filter = new JwtAuthFilter(svc);
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/entity/x/list");
req.addHeader("Authorization", "Bearer " + token);
MockHttpServletResponse resp = new MockHttpServletResponse();
// 下游链断言:链执行期间上下文已填充
AtomicBoolean ctxSeenInChain = new AtomicBoolean(false);
MockFilterChain chain = new MockFilterChain() {
@Override
public void doFilter(jakarta.servlet.ServletRequest request,
jakarta.servlet.ServletResponse response) {
Properties ctx = UserSession.get();
ctxSeenInChain.set(ctx != null
&& "USER_BOB".equals(ctx.getProperty(LoggedInUser.CURRENTUSER)));
}
};
filter.doFilter(req, resp, chain);
assertTrue(ctxSeenInChain.get(), "过滤器链执行期间引擎上下文应已填充为 USER_BOB");
assertNull(UserSession.get(), "过滤器 finally 后引擎上下文必须清空");
}
@Test
void 无令牌不填充上下文且收尾干净() throws Exception {
JwtAuthFilter filter = new JwtAuthFilter(jwtService());
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/entity/x/list");
MockHttpServletResponse resp = new MockHttpServletResponse();
AtomicBoolean emptyInChain = new AtomicBoolean(false);
MockFilterChain chain = new MockFilterChain() {
@Override
public void doFilter(jakarta.servlet.ServletRequest request,
jakarta.servlet.ServletResponse response) {
emptyInChain.set(UserSession.get() == null);
}
};
filter.doFilter(req, resp, chain);
assertTrue(emptyInChain.get(), "无令牌时不应填充引擎上下文(留给 asUser/roles 旁路或 ADMIN 视角)");
assertNull(UserSession.get());
}
@Test
void 并发不同令牌各自隔离不串号() throws Exception {
JwtService svc = jwtService();
JwtAuthFilter filter = new JwtAuthFilter(svc);
int threads = 16;
int iterations = 200;
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(threads);
// 收集任何串号:key=期望 userId,value=实际观测到的不一致 userId
ConcurrentHashMap<String, String> leaks = new ConcurrentHashMap<>();
AtomicBoolean residueAfter = new AtomicBoolean(false);
for (int i = 0; i < threads; i++) {
String userId = "USER_" + i;
String role = "ROLE_" + i;
String token = svc.issue(new AuthPrincipal(userId, "acc" + i, "n" + i,
null, null, List.of(role)));
pool.submit(() -> {
try {
start.await();
for (int k = 0; k < iterations; k++) {
MockHttpServletRequest req =
new MockHttpServletRequest("GET", "/api/entity/x/list");
req.addHeader("Authorization", "Bearer " + token);
MockHttpServletResponse resp = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain() {
@Override
public void doFilter(jakarta.servlet.ServletRequest rq,
jakarta.servlet.ServletResponse rs) {
Properties ctx = UserSession.get();
String seen = ctx == null ? null
: ctx.getProperty(LoggedInUser.CURRENTUSER);
if (!userId.equals(seen)) {
leaks.put(userId, String.valueOf(seen));
}
@SuppressWarnings("unchecked")
List<String> roles = ctx == null ? null
: (List<String>) ctx.get(LoggedInUser.ROLES);
if (roles == null || !roles.equals(List.of(role))) {
leaks.put(userId + "#roles", String.valueOf(roles));
}
}
};
filter.doFilter(req, resp, chain);
// 每次请求收尾后,本线程上下文必须已清空
if (UserSession.get() != null) {
residueAfter.set(true);
}
}
} catch (Exception e) {
leaks.put("EXC", e.toString());
} finally {
done.countDown();
}
});
}
start.countDown();
assertTrue(done.await(60, TimeUnit.SECONDS), "并发任务应在超时内完成");
pool.shutdownNow();
assertTrue(leaks.isEmpty(), "并发下不得串号/泄漏,实际异常: " + leaks);
assertTrue(!residueAfter.get(), "每次请求收尾后线程上不得残留引擎上下文");
}
}

View File

@@ -0,0 +1,119 @@
package com.eip4.platform.auth.security;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import io.jsonwebtoken.JwtException;
/**
* JWT 签发/校验/过期/伪造 单测(不起 Spring 上下文,直接构造 JwtService)。
*/
class JwtServiceTest {
private static final String SECRET = "unit-test-secret-key-which-is-long-enough-0123456789";
private static JwtService service(long expireSeconds) {
JwtProperties p = new JwtProperties();
p.setSecret(SECRET);
p.setExpireSeconds(expireSeconds);
p.setIssuer("eip4-platform");
return new JwtService(p);
}
private static AuthPrincipal sample() {
return new AuthPrincipal("USER_ALICE", "alice", "爱丽丝",
"DEPT_A", "ORG_1", List.of("ROLE_CUSTOMER", "ROLE_TASK"));
}
@Test
void 签发并回读全部claim() {
JwtService svc = service(3600);
String token = svc.issue(sample());
AuthPrincipal back = svc.parse(token);
assertEquals("USER_ALICE", back.userId());
assertEquals("alice", back.account());
assertEquals("爱丽丝", back.name());
assertEquals("DEPT_A", back.depart());
assertEquals("ORG_1", back.org());
assertEquals(List.of("ROLE_CUSTOMER", "ROLE_TASK"), back.roles());
}
@Test
void 过期令牌校验失败() {
// 负有效期 → 签发即已过期
JwtService svc = service(-10);
String token = svc.issue(sample());
assertThrows(JwtException.class, () -> svc.parse(token));
}
@Test
void 异密钥伪造令牌被拒() {
JwtService issuer = service(3600);
String token = issuer.issue(sample());
JwtProperties other = new JwtProperties();
other.setSecret("a-totally-different-secret-key-also-long-enough-9876543210");
other.setIssuer("eip4-platform");
JwtService verifier = new JwtService(other);
assertThrows(JwtException.class, () -> verifier.parse(token));
}
@Test
void 篡改令牌串被拒() {
JwtService svc = service(3600);
String token = svc.issue(sample());
// 翻转 payload 段末位字符,破坏签名一致性
String tampered = token.substring(0, token.length() - 1)
+ (token.endsWith("A") ? "B" : "A");
assertThrows(JwtException.class, () -> svc.parse(tampered));
}
@Test
void issuer不符被拒() {
JwtProperties issuerProps = new JwtProperties();
issuerProps.setSecret(SECRET);
issuerProps.setIssuer("someone-else");
JwtService foreignIssuer = new JwtService(issuerProps);
String token = foreignIssuer.issue(sample());
JwtService ours = service(3600); // issuer = eip4-platform
assertThrows(JwtException.class, () -> ours.parse(token));
}
@Test
void 密钥缺失则构造失败() {
JwtProperties p = new JwtProperties();
p.setSecret(" ");
assertThrows(IllegalStateException.class, () -> new JwtService(p));
}
@Test
void 密钥过短则构造失败() {
JwtProperties p = new JwtProperties();
p.setSecret("short"); // < 32 字节
assertThrows(IllegalStateException.class, () -> new JwtService(p));
}
@Test
void 乱码非JWT串被拒() {
JwtService svc = service(3600);
assertThrows(RuntimeException.class, () -> svc.parse("not-a-jwt-token"));
}
@Test
void md5口令哈希与框架口径一致() {
// framework EncryptUtil.encodeMD5String("123456") 的标准小写十六进制 MD5
assertEquals("e10adc3949ba59abbe56e057f20f883e",
PasswordHasher.md5Hex("123456"));
assertTrue(PasswordHasher.matches("e10adc3949ba59abbe56e057f20f883e", "123456"));
assertFalse(PasswordHasher.matches("e10adc3949ba59abbe56e057f20f883e", "wrong"));
}
}

View File

@@ -0,0 +1,86 @@
package com.eip4.platform.auth.security;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.FilterChainProxy;
import jakarta.servlet.http.HttpServletResponse;
/**
* 安全链按 profile 装配的断言:
* <ul>
* <li><b>生产链(prod)</b>:测试旁路<strong>关闭</strong>——无令牌访问 /api/entity/** 被拒(401/403,非 2xx);
* 放行清单(/api/auth/**、/v3/api-docs/**)仍开。</li>
* <li><b>非生产链(无 profile)</b>:permitAll 测试通道开启——无令牌访问 /api/entity/** 放行(对拍 CI 依赖)。</li>
* </ul>
* 用 WebApplicationContextRunner 直接装载 SecurityConfig + 真实 Security 自动配置,
* 取出 springSecurityFilterChain 跑 Mock 请求观察拦截结果,不需起整 Boot 应用。
*/
class SecurityProfileTest {
private static final String SECRET = "profile-test-secret-key-long-enough-abcdefghijklmnopqr";
private WebApplicationContextRunner runner() {
JwtProperties props = new JwtProperties();
props.setSecret(SECRET);
props.setIssuer("eip4-platform");
JwtService jwt = new JwtService(props);
return new WebApplicationContextRunner()
.withConfiguration(org.springframework.boot.autoconfigure.AutoConfigurations.of(
SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class))
.withBean(JwtService.class, () -> jwt)
.withUserConfiguration(SecurityConfig.class);
}
/** 经 springSecurityFilterChain 跑一个 mock 请求,返回最终响应状态码(被拦则非 200)。 */
private int statusThroughChain(org.springframework.context.ApplicationContext ctx,
String method, String uri) throws Exception {
FilterChainProxy chain = ctx.getBean("springSecurityFilterChain", FilterChainProxy.class);
MockHttpServletRequest req = new MockHttpServletRequest(method, uri);
req.setServletPath(uri);
MockHttpServletResponse resp = new MockHttpServletResponse();
// 终端链:若安全链放行到此,则置 200;若安全链已拒(401/403),resp 已被写入状态
chain.doFilter(req, resp, (rq, rs) -> ((HttpServletResponse) rs).setStatus(200));
return resp.getStatus();
}
@Test
void 生产链关闭测试旁路_受保护路径无令牌被拒() {
runner().withPropertyValues("spring.profiles.active=prod").run(ctx -> {
assertThat(ctx).hasNotFailed();
int protectedStatus = statusThroughChain(ctx, "GET", "/api/entity/EIP4PT_TASK/list");
assertThat(protectedStatus)
.as("生产 profile:受保护 API 无令牌必须被拒为 401(凭据缺失)")
.isEqualTo(401);
});
}
@Test
void 生产链仍放行登录端点与API文档() {
runner().withPropertyValues("spring.profiles.active=prod").run(ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(statusThroughChain(ctx, "POST", "/api/auth/login"))
.as("登录端点须放行").isEqualTo(200);
assertThat(statusThroughChain(ctx, "GET", "/v3/api-docs"))
.as("OpenAPI 文档须放行").isEqualTo(200);
});
}
@Test
void 非生产链开启测试旁路_无令牌放行() {
// 无 active profile → devFilterChain(@Profile("!prod"))
runner().run(ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(statusThroughChain(ctx, "GET", "/api/entity/EIP4PT_TASK/list"))
.as("非生产 profile:permitAll 测试通道开启,无令牌应放行(对拍 CI 依赖)")
.isEqualTo(200);
});
}
}