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:
19
docs/迁移手册.md
19
docs/迁移手册.md
@@ -373,6 +373,25 @@ com.dsasp.* com.eip4.*
|
||||
- **对策**:① 第一类按 §7.2 元数据漂移处置(对齐元数据或物理表,客户确认);② 第二类是引擎读路径真缺陷,取证待引擎侧修复。对拍 harness 如实记 ENGINE_ERROR + 500 body,不豁免。
|
||||
- **影响范围**:8 个实体;与 §7.1/§7.2 PoC 计数级口径互证(本轮逐个落实根因)。
|
||||
|
||||
### 5.29 JWT 上下文被 EntityController 的 ADMIN 默认覆盖(认证集成坑)[NEW 2026-06-11]
|
||||
|
||||
- **现象**:`JwtAuthFilter` 已把 JWT claims(CURRENTUSER=真实 userId + ROLES)写入引擎 `UserSession`,但带令牌调 `/api/entity/{t}/list` 仍返回全量(不过滤)。
|
||||
- **根因**:`EntityController.buildCtx(asUser, roles)` 在无 `asUser` 查询参时**无条件返回 `UserSession.getAdmin()`**,覆盖了过滤器刚绑定的请求级上下文;ADMIN 视角天然不触发行级过滤(引擎仅 `CURRENTUSER != ADMIN` 时调 `dataPrivilegeService`,见 §5.9)。
|
||||
- **对策**:`buildCtx` 改为三级优先:① 显式 `asUser` 参(C2 对拍测试通道,CI 依赖)优先;② 否则复用 `UserSession.get()` 已绑定的非 ADMIN 上下文(JWT 驱动);③ 都没有才回退 ADMIN。如此 **JWT roles 替代 asUser/roles 参数**驱动过滤,且对拍旁路零回归(full CI 21/21 + C2 9/9 仍绿)。
|
||||
- **影响范围**:凡「过滤器绑 ThreadLocal 上下文 + 控制器又自建 ctx」的端点都有此覆盖风险;新端点须遵循「过滤器绑定优先于控制器默认」。
|
||||
|
||||
### 5.30 引擎 UserSession 是静态 ThreadLocal,认证过滤器必须请求级 set/clear [NEW 2026-06-11]
|
||||
|
||||
- **现象/契约**:`com.dsasp.server.common.util.UserSession` 是**静态 `ThreadLocal<Properties>`**;引擎全程从当前线程取 `CURRENTUSER/CURRENTDEPART/CURRENTORG`(字符串)与 `ROLES`(**List,用 `put` 非 `setProperty`**——引擎 `ctx.get("ROLES")` 强转 `List<String>`)。
|
||||
- **坑**:Tomcat 复用工作线程;若 filter 只 set 不 clear,下一请求会**继承上一请求身份**(跨请求泄漏)。
|
||||
- **对策**:`JwtAuthFilter` 在 `try` 中 `EngineContextBinder.bind`,`finally` 中**无条件 `clear`**(即便下游抛异常)。并发隔离由 `EngineContextIsolationTest`(16 线程×200 次不同令牌)断言零串号 + 收尾零残留。`ROLES` 必须 `put(List)` 不可 `setProperty`,否则引擎强转 ClassCastException。
|
||||
|
||||
### 5.31 客户库 SYS_USER 口令哈希=无盐小写十六进制 MD5(侦察结论)[NEW 2026-06-11]
|
||||
|
||||
- **侦察证据**(读 framework 源码核实):`com.dsasp.server.common.util.EncryptUtil.encodeMD5String` = `MessageDigest("MD5").digest(str.getBytes())` 逐字节小写十六进制(`b<16` 补前导 0),32 字符,**无盐、无迭代**;登录比对为 `hash.equals(SYS_USER.PASSWORD)` 纯字符串相等(见 `AuthConstroller#login`、`ChangePasswordView`、`LoginWindow`→`SYS_USER_SEARCH` 流按 ACCOUNT+PASSWORD 查)。
|
||||
- **落地**:platform-auth 在 `com.eip4` 侧**逐字节复刻** `PasswordHasher.md5Hex`(保真层 EncryptUtil 一行不改),用平台默认字符集 `getBytes()` 与旧系统一致;比对用 `MessageDigest.isEqual` 常量时间防时序侧信道。验证:`MD5("123456")=e10adc3949ba59abbe56e057f20f883e` 单测断言。
|
||||
- **注意**:无盐 MD5 是**待现代化项**(口令存储弱),但本任务目标是兼容验证既有客户库口令,口令强化属后续独立议题(可在改密路径渐进迁移)。角色解析复刻 `RoleServiceImpl#findRolesByUserId`(`sys_usergrouprole ⋈ sys_usergroupuser`),org 表未移植时降级空角色不阻断登录。
|
||||
|
||||
## 六、Flowable 升级三坑
|
||||
|
||||
> 来源:eip4-poc WS4 实测,flowable-poc / flowable5-poc 工程(2026-06-10)
|
||||
|
||||
@@ -17,6 +17,15 @@ spring:
|
||||
server:
|
||||
port: 8084
|
||||
|
||||
# 认证(P2):本地自举默认 JWT 密钥。仅本地/对拍用,生产须经
|
||||
# EIP4_AUTH_JWT_SECRET 覆盖 + profile=prod 启严格链。详见 application.yml 注释。
|
||||
eip4:
|
||||
auth:
|
||||
jwt:
|
||||
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
||||
expire-seconds: 28800 # 8h
|
||||
issuer: eip4-platform
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.dsasp: INFO
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
spring:
|
||||
application:
|
||||
name: eip4-poc
|
||||
autoconfigure:
|
||||
# 认证走 JWT(非表单/Basic),排除默认内存用户管理:免生成误导性 dev 口令、免无用 AuthManager
|
||||
exclude:
|
||||
- org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
|
||||
datasource:
|
||||
url: jdbc:postgresql://192.168.20.68:5435/postgres?currentSchema=eip3
|
||||
username: ceshi
|
||||
@@ -13,6 +17,19 @@ spring:
|
||||
server:
|
||||
port: 8084
|
||||
|
||||
# ============================================================================
|
||||
# 认证(P2):无状态 JWT。HS256 对称密钥配置化,严禁硬编码进 Java 代码。
|
||||
# 下方为「非生产默认值」——供 default/local/ci profile 自举开箱即用。
|
||||
# 生产部署务必经环境变量 EIP4_AUTH_JWT_SECRET 覆盖为强随机密钥(≥32 字节),
|
||||
# 并以 -Dspring.profiles.active=prod 启用严格安全链(其余 /api/** 强制认证)。
|
||||
# ============================================================================
|
||||
eip4:
|
||||
auth:
|
||||
jwt:
|
||||
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
||||
expire-seconds: 28800 # 8h
|
||||
issuer: eip4-platform
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.dsasp: DEBUG
|
||||
|
||||
183
platform-auth/P2认证实测报告.md
Normal file
183
platform-auth/P2认证实测报告.md
Normal file
@@ -0,0 +1,183 @@
|
||||
# EIP4 P2-2 任务 实测报告 —— Spring Security + 无状态 JWT + UserSession 适配
|
||||
|
||||
> 工程:eip4-platform · 环境:本地 PG 15(`localhost:5433`),实测端口 8086/8087,连本地库自举
|
||||
> 时间:2026-06-11 · 通过标准:登录签发 JWT + 带/不带/伪造/过期令牌行为正确 + JWT roles 驱动行级过滤 + 单测 ≥8
|
||||
> **保真层 `com.dsasp` 一行未改**,适配全部在 `com.eip4.platform.auth.security`。
|
||||
|
||||
## 一、结论速览
|
||||
|
||||
| 项 | 结果 |
|
||||
|----|------|
|
||||
| 密码哈希侦察(读 framework 源码) | ✅ **无盐小写十六进制 MD5**,纯字符串相等比对 |
|
||||
| JWT 选型 | ✅ **jjwt 0.12.6**(HS256 对称密钥,理由见 §三) |
|
||||
| POST /api/auth/login 签发 JWT | ✅ 账号口令校验 SYS_USER → 签发含 userId/账号/姓名/depart/org/roles |
|
||||
| JwtAuthFilter 填充引擎 ctx + 请求级清理 | ✅ set/clear,**并发隔离单测断言零泄漏** |
|
||||
| SecurityConfig 双链按 profile | ✅ 非 prod 保留 permitAll+asUser/roles 测试通道;**prod 严格,无旁路** |
|
||||
| 实测 401(无/伪造/过期令牌) | ✅ 全部 401 |
|
||||
| 实测 JWT roles 驱动行级过滤 | ✅ 带 alice 令牌读 3 受控实体各 **16 行**(=alice 的行,非全量 50) |
|
||||
| 单测 | ✅ **16 用例全过**(要求 ≥8) |
|
||||
| CI 兼容(`scripts/ci.sh`,含 parity) | ✅ **全绿**:21/21 实体 1108 行 + C2 9/9 正例 + 3/3 负例 |
|
||||
|
||||
---
|
||||
|
||||
## 二、密码哈希侦察(证据)
|
||||
|
||||
侦察对象:`/Users/zhengwr/workspace/eip3/framework`(旧系统源码)。读到的口径逐条:
|
||||
|
||||
1. **哈希函数**:`com.dsasp.server.common.util.EncryptUtil.encodeMD5String`:
|
||||
```java
|
||||
MessageDigest md5 = MessageDigest.getInstance("MD5");
|
||||
byte[] bytes = md5.digest(str.getBytes()); // 平台默认字符集
|
||||
// 逐字节小写十六进制,b<16 补前导 0 → 32 字符
|
||||
```
|
||||
→ **标准小写十六进制 MD5,无盐、无迭代**。
|
||||
2. **登录比对(服务端,`AuthConstroller#login`)**:按 `SYS_USER_SEARCH` 服务流,
|
||||
`P.ACCOUNT = '<账号>'` + `PASSWORD = EncryptUtil.encodeMD5String(明文)`,纯相等命中。
|
||||
3. **改密(`ChangePasswordView`)**:`oldPwd.equals(entity.get_Value("PASSWORD"))`、
|
||||
`map.put("PASSWORD", encodeMD5String(新明文))` 落库 → 印证存储即该 MD5、比对即 `equals`。
|
||||
4. **UI 登录(`LoginWindow`)**:同走 `SYS_USER_SEARCH`(按 ACCOUNT)取用户行;ctx 构建口径
|
||||
(注释段)= `CURRENTUSER=pojo.get_ID()`、`CURRENTDEPART=MASTERDEPART`、`CURRENTORG=USERORGID`、
|
||||
`ROLES=roleService.findRolesByUserId(userId)`——**这就是我适配引擎 ctx 的精确契约**。
|
||||
|
||||
**复刻**:`com.eip4.platform.auth.security.PasswordHasher.md5Hex` 逐字节复刻(保真层不动),
|
||||
比对用 `MessageDigest.isEqual` 常量时间。单测断言 `MD5("123456")=e10adc3949ba59abbe56e057f20f883e`。
|
||||
|
||||
> 已同步《迁移手册》§5.31。
|
||||
|
||||
---
|
||||
|
||||
## 三、JWT 选型(jjwt vs spring-security-oauth2-jose)
|
||||
|
||||
**选 jjwt 0.12.6**,理由:
|
||||
- 本系统是**自签自验**的单一签发方,不与外部 IdP 联邦、无需 JWKS/非对称密钥轮转 →
|
||||
HS256 + 配置化对称密钥即足够;oauth2-jose/资源服务器栈面向 OAuth2 联邦,在此属过度设计。
|
||||
- jjwt API 精简,0.12.x 强制安全默认(密钥长度校验、算法绑定),契合「最小可用」。
|
||||
- 与架构选型表「Spring Security + 无状态 JWT,免 session 共享」一致。
|
||||
|
||||
**密钥不硬编码进仓库**:`JwtService` 构造期校验密钥存在且 ≥32 字节(HS256),缺失/过短直接启动失败。
|
||||
本地默认值仅放 `application.yml`/`application-local.yml`(`${EIP4_AUTH_JWT_SECRET:dev-only-...}`,
|
||||
注明生产须替换);生产经环境变量 `EIP4_AUTH_JWT_SECRET` 覆盖。
|
||||
> 注:CI 用 default profile,故 default 配置须有可启动的非生产默认密钥(已加注释强标「生产须替换」)。
|
||||
|
||||
JWT claims:`iss/sub(账号)/userId/account/name/depart/org/roles(List)/iat/exp`;有效期默认 8h(可配)。
|
||||
|
||||
---
|
||||
|
||||
## 四、组件清单(全部 com.eip4.platform.auth.security)
|
||||
|
||||
| 类 | 职责 |
|
||||
|----|------|
|
||||
| `JwtProperties` | `eip4.auth.jwt.*` 配置(secret/expireSeconds/issuer),无内置默认密钥 |
|
||||
| `JwtService` | HS256 签发/校验(过期/签名/issuer 校验);启动期密钥强度校验 |
|
||||
| `PasswordHasher` | 复刻 EncryptUtil 的无盐 MD5 + 常量时间比对 |
|
||||
| `SysUserService` | 只读 SELECT 校验 SYS_USER(按 ACCOUNT)+ 角色解析(复刻 RoleServiceImpl join,参数化) |
|
||||
| `AuthPrincipal` | JWT claims 不可变载体(record),映射 SYS_USER 列与 LoggedInUser 契约 |
|
||||
| `AuthController` | `POST /api/auth/login`,失败统一 401 含糊文案(防账号枚举) |
|
||||
| `EngineContextBinder` | 把 AuthPrincipal 写入引擎 UserSession(ROLES 用 put(List));bind/clear |
|
||||
| `JwtAuthFilter` | 校验 Bearer → SecurityContext + 引擎 ctx;**finally 无条件 clear** |
|
||||
| `SecurityConfig` | 双链按 profile:prod 严格(未认证 401),非 prod permitAll 测试通道 |
|
||||
| `AuthConfig` | `@EnableConfigurationProperties(JwtProperties)` |
|
||||
|
||||
**EntityController 适配(platform-metadata)**:`buildCtx` 三级优先(asUser 参 > JWT 绑定 ctx > ADMIN),
|
||||
使 JWT roles 替代 asUser/roles 驱动行级过滤,且 C2 对拍旁路零回归。详见《迁移手册》§5.29。
|
||||
|
||||
---
|
||||
|
||||
## 五、实测证据(curl)
|
||||
|
||||
### 5.1 登录签发 JWT(8086,连 eip4ci 自举库)
|
||||
|
||||
```
|
||||
POST /api/auth/login {"account":"alice","password":"123456"}
|
||||
→ HTTP 200
|
||||
{"success":true,"token":"eyJ...","expireSeconds":28800,
|
||||
"userId":"USER_ALICE","account":"alice","name":"爱丽丝",
|
||||
"roles":["ROLE_CUSTOMER","ROLE_PROJECT","ROLE_TASK"]}
|
||||
```
|
||||
|
||||
### 5.2 JWT roles 驱动行级过滤(复用 C2 的 3 受控实体)
|
||||
|
||||
带 alice 令牌(CURRENTUSER=USER_ALICE,roles=[ROLE_CUSTOMER/PROJECT/TASK])调受控实体,
|
||||
引擎按 `CREATEBY={CURRENTUSERID}` 过滤,**仅返回 alice 的行**:
|
||||
|
||||
| 场景 | 实体 | HTTP | 返回行数 | 期望 |
|
||||
|------|------|------|---------|------|
|
||||
| 带令牌(JWT roles) | EIP4PT_CUSTOMER | 200 | **16** | alice 16 行(非全量 50)✅ |
|
||||
| 带令牌(JWT roles) | EIP4PT_PROJECT | 200 | **16** | ✅ |
|
||||
| 带令牌(JWT roles) | EIP4PT_TASK | 200 | **16** | ✅ |
|
||||
| 无令牌无 asUser | EIP4PT_CUSTOMER | 200 | 50 | ADMIN 视角不过滤(默认不变)✅ |
|
||||
| C2 旁路 ?asUser=USER_BOB | EIP4PT_CUSTOMER | 200 | 17 | 测试通道仍可用 ✅ |
|
||||
|
||||
DB ground truth(CREATEBY 重分区后):ALICE 16 / BOB 17 / CAROL 17,逐数吻合。
|
||||
> JWT roles 成功**替代** asUser/roles 参数:同一引擎过滤路径,身份来源从查询参换成 JWT claims。
|
||||
|
||||
### 5.3 严格鉴权(prod profile,8087)
|
||||
|
||||
| 场景 | HTTP | 期望 |
|
||||
|------|------|------|
|
||||
| 登录正确口令 | 200 | 签发令牌 ✅ |
|
||||
| 登录错误口令 | 401 | 拒绝 ✅ |
|
||||
| 无令牌访问 /api/entity/** | **401** | 拒绝(凭据缺失)✅ |
|
||||
| 伪造签名令牌 | **401** | 拒绝 ✅ |
|
||||
| 乱码令牌 | **401** | 拒绝 ✅ |
|
||||
| 已过期令牌(expire=-3600s) | **401** | 拒绝 ✅ |
|
||||
| 带有效令牌访问 /api/entity/** | 200 | 放行 + 过滤 16 行 ✅ |
|
||||
|
||||
> prod 链经 `HttpStatusEntryPoint(UNAUTHORIZED)` 使未认证返回 401(而非 Spring 默认 403,语义更正确)。
|
||||
> 并排除 `UserDetailsServiceAutoConfiguration`,免生成误导性 dev 口令(JWT 认证不需内存用户)。
|
||||
|
||||
---
|
||||
|
||||
## 六、单测(16 用例,platform-auth)
|
||||
|
||||
`JwtServiceTest`(9):签发回读全 claim、过期被拒、异密钥伪造被拒、篡改串被拒、issuer 不符被拒、
|
||||
密钥缺失/过短构造失败、乱码非 JWT 被拒、MD5 口令哈希与框架口径一致。
|
||||
|
||||
`EngineContextIsolationTest`(4):bind 写入再 clear 清空、过滤器请求收尾后清空、无令牌不填充、
|
||||
**16 线程×200 次不同令牌并发零串号 + 收尾零残留**(并发隔离证明)。
|
||||
|
||||
`SecurityProfileTest`(3):**prod 链受保护路径无令牌=401**(测试旁路关闭断言)、
|
||||
prod 链仍放行登录端点与 API 文档、非 prod 链 permitAll 旁路开启(对拍 CI 依赖)。
|
||||
|
||||
```
|
||||
Tests run: 16, Failures: 0, Errors: 0, Skipped: 0 —— BUILD SUCCESS
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 七、CI 兼容
|
||||
|
||||
`scripts/ci.sh`(default profile,连 eip4ci):
|
||||
- `--skip-parity`:编译 + 全模块单测 + ArchUnit 边界纪律 → 绿。
|
||||
- 完整(含 parity):**21/21 实体 1108 行 100% 逐行一致** + C2 权限对拍 **9/9 正例 + 3/3 负例**全过。
|
||||
|
||||
> 关键:CI 用 default(非 prod)profile,安全层走 permitAll 测试通道,parity 的免令牌 +
|
||||
> asUser/roles 旁路**零回归**——证明安全层接入未破坏对拍门禁。ArchUnit 仍绿(新代码仅依赖
|
||||
> com.dsasp 的 UserSession/LoggedInUser,反向零依赖)。
|
||||
|
||||
---
|
||||
|
||||
## 八、自举数据(bootstrap-auth.sql)
|
||||
|
||||
位置:`platform-parity/src/main/resources/bootstrap/bootstrap-auth.sql`(幂等,在 sys+privilege 之后追加)。
|
||||
内容:① SYS_USER 物理表(认证读路径列);② 测试用户 alice(SYS_USER_ID='USER_ALICE',口令 123456 的 MD5);
|
||||
③ 用户组/角色链(sys_usergroupuser ⋈ sys_usergrouprole,复刻 RoleServiceImpl 读路径)→ alice 得
|
||||
ROLE_CUSTOMER/PROJECT/TASK;④ 受控实体 CREATEBY 重分区(与 privilege 脚本同口径,使过滤可判别)。
|
||||
|
||||
---
|
||||
|
||||
## 九、新坑(已同步《迁移手册》)
|
||||
|
||||
- §5.29 JWT 上下文被 EntityController 的 ADMIN 默认覆盖(认证集成坑)。
|
||||
- §5.30 引擎 UserSession 是静态 ThreadLocal,认证过滤器必须请求级 set/clear(ROLES 用 put(List))。
|
||||
- §5.31 客户库 SYS_USER 口令哈希=无盐小写十六进制 MD5(侦察结论)。
|
||||
|
||||
## 附:产物清单
|
||||
|
||||
- 实现:`platform-auth/src/main/java/com/eip4/platform/auth/security/`(10 类)
|
||||
- 适配:`platform-metadata/.../web/EntityController.java`(buildCtx 三级优先)
|
||||
- 配置:`pom.xml`(jjwt dependencyManagement)、`platform-auth/pom.xml`(security/jwt/jdbc)、
|
||||
`platform-app/.../application.yml` + `application-local.yml`(JWT 配置 + 排除 UserDetailsService 自动配)
|
||||
- 自举:`platform-parity/.../bootstrap/bootstrap-auth.sql`
|
||||
- 单测:`platform-auth/src/test/.../security/`(3 类 16 用例)
|
||||
- 报告:本文件;新坑进《迁移手册》§5.29/5.30/5.31
|
||||
@@ -13,6 +13,16 @@
|
||||
<description>P2:组织/权限/数据权限真实现(当前为 PoC 桩 + C2 数据权限最小真实现)</description>
|
||||
<dependencies>
|
||||
<dependency><groupId>com.eip4</groupId><artifactId>platform-legacy-core</artifactId></dependency>
|
||||
<!-- 认证四层:Spring Security 过滤链 + Web(登录端点/JWT 过滤器) -->
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
|
||||
<!-- 校验客户库 SYS_USER:只读 SELECT(JdbcTemplate),不引 ORM(与架构选型表一致) -->
|
||||
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
|
||||
<!-- 无状态 JWT 签发/校验 -->
|
||||
<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-jackson</artifactId><scope>runtime</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>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<Properties></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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
}
|
||||
@@ -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(), "每次请求收尾后线程上不得残留引擎上下文");
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -130,25 +130,41 @@ public class EntityController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造调用上下文。无 asUser → ADMIN 视角(不触发过滤);有 asUser → 非 ADMIN 视角,
|
||||
* 把 CURRENTUSER 与 ROLES(List)放入 Properties,交由引擎按 SYS_FILTERRULE 规则过滤。
|
||||
* 构造调用上下文,优先级:
|
||||
* <ol>
|
||||
* <li><b>显式 asUser 查询参</b>(C2 对拍测试通道,CI 依赖)→ 非 ADMIN 视角,触发行级过滤。</li>
|
||||
* <li><b>JWT 已绑定的引擎上下文</b>:{@code JwtAuthFilter} 已把 JWT claims 写入
|
||||
* 请求级 {@code UserSession}(CURRENTUSER=真实 userId + ROLES)。无 asUser 时
|
||||
* 直接复用该绑定上下文,使<strong>JWT roles 替代 asUser/roles 参数</strong>驱动行级过滤。</li>
|
||||
* <li><b>都没有</b>(无令牌、无 asUser)→ ADMIN 视角,不过滤(与原默认行为一致)。</li>
|
||||
* </ol>
|
||||
*/
|
||||
private Properties buildCtx(String asUser, String roles) {
|
||||
if (asUser == null || asUser.isBlank()) {
|
||||
return UserSession.getAdmin();
|
||||
}
|
||||
Properties ctx = new Properties();
|
||||
ctx.setProperty(LoggedInUser.CURRENTUSER, asUser);
|
||||
List<String> roleList = new ArrayList<>();
|
||||
if (roles != null && !roles.isBlank()) {
|
||||
for (String r : roles.split(",")) {
|
||||
if (!r.isBlank()) {
|
||||
roleList.add(r.trim());
|
||||
// 1) 显式 asUser 测试通道优先(保持 C2 既有行为不变)
|
||||
if (asUser != null && !asUser.isBlank()) {
|
||||
Properties ctx = new Properties();
|
||||
ctx.setProperty(LoggedInUser.CURRENTUSER, asUser);
|
||||
List<String> roleList = new ArrayList<>();
|
||||
if (roles != null && !roles.isBlank()) {
|
||||
for (String r : roles.split(",")) {
|
||||
if (!r.isBlank()) {
|
||||
roleList.add(r.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.put(LoggedInUser.ROLES, roleList);
|
||||
return ctx;
|
||||
}
|
||||
ctx.put(LoggedInUser.ROLES, roleList);
|
||||
return ctx;
|
||||
// 2) JWT 过滤器已绑定的请求级上下文(非 ADMIN 真实用户)→ 复用,驱动行级过滤
|
||||
Properties bound = UserSession.get();
|
||||
if (bound != null) {
|
||||
String cu = bound.getProperty(LoggedInUser.CURRENTUSER);
|
||||
if (cu != null && !cu.isBlank() && !LoggedInUser.ADMIN.trim().equals(cu.trim())) {
|
||||
return bound;
|
||||
}
|
||||
}
|
||||
// 3) 默认 ADMIN 视角(无令牌、无 asUser)
|
||||
return UserSession.getAdmin();
|
||||
}
|
||||
|
||||
/** GeneralPOJO 值存于内部数组(非 bean getter),手工展开为平面 map 供 JSON 序列化。 */
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
-- ===========================================================================
|
||||
-- bootstrap-auth.sql —— P2 认证自举(SYS_USER + 用户组/角色链 + CREATEBY 重分区)
|
||||
-- 幂等,可重复执行;在 bootstrap-sys.sql + bootstrap-privilege.sql 之后追加。
|
||||
--
|
||||
-- 目的:为 platform-auth 的「登录 → 签发 JWT → JWT roles 驱动行级过滤」端到端实测
|
||||
-- 准备本地最小数据:
|
||||
-- 1) SYS_USER 物理表(列对齐 framework SYS_USER_SEARCH 读路径所需:ACCOUNT/PASSWORD/
|
||||
-- NAME/MASTERDEPART/USERORGID/SYS_USER_ID)。
|
||||
-- 2) 1 个测试用户 alice:SYS_USER_ID='USER_ALICE'(=引擎 CURRENTUSER,使
|
||||
-- CREATEBY={CURRENTUSERID} 过滤命中 alice 的行),口令明文 123456
|
||||
-- → MD5(小写十六进制)=e10adc3949ba59abbe56e057f20f883e(与 EncryptUtil 一致)。
|
||||
-- 3) 用户组/角色链(sys_usergroupuser ⋈ sys_usergrouprole),复刻
|
||||
-- RoleServiceImpl#findRolesByUserId 读路径;alice → ROLE_CUSTOMER/ROLE_PROJECT/ROLE_TASK
|
||||
-- (与 bootstrap-privilege.sql 的受控实体角色一致,JWT roles 即可替代 asUser/roles)。
|
||||
-- 4) 受控实体 CREATEBY 重分区(与 privilege 脚本同口径),使过滤可判别。
|
||||
-- 注意:本脚本仅用于本地/对拍自举;不进生产数据。
|
||||
-- ===========================================================================
|
||||
|
||||
-- 1. SYS_USER 物理表(仅认证读路径所需列,char(36) 主键与 framework 一致)
|
||||
CREATE TABLE IF NOT EXISTS sys_user (
|
||||
sys_user_id character(36) NOT NULL,
|
||||
account varchar(100),
|
||||
password varchar(100),
|
||||
name varchar(100),
|
||||
masterdepart character(36),
|
||||
userorgid character(36),
|
||||
isactive integer DEFAULT 1,
|
||||
createby character(36),
|
||||
updateby character(36),
|
||||
createtime bigint DEFAULT 0,
|
||||
updatetime bigint DEFAULT 0,
|
||||
version integer DEFAULT 0,
|
||||
PRIMARY KEY (sys_user_id)
|
||||
);
|
||||
|
||||
-- 2. 测试用户 alice(幂等 upsert):口令 123456 的 MD5
|
||||
INSERT INTO sys_user
|
||||
(sys_user_id, account, password, name, masterdepart, userorgid, isactive, createby, updateby)
|
||||
VALUES
|
||||
('USER_ALICE', 'alice', 'e10adc3949ba59abbe56e057f20f883e', '爱丽丝',
|
||||
'DEPT_A', 'ORG_1', 1, 'ADMIN', 'ADMIN')
|
||||
ON CONFLICT (sys_user_id) DO UPDATE SET
|
||||
account = EXCLUDED.account, password = EXCLUDED.password,
|
||||
name = EXCLUDED.name, masterdepart = EXCLUDED.masterdepart,
|
||||
userorgid = EXCLUDED.userorgid, isactive = 1;
|
||||
|
||||
-- 3. 用户组/角色链(复刻 RoleServiceImpl 读路径:user→group→role)
|
||||
CREATE TABLE IF NOT EXISTS sys_usergroupuser (
|
||||
usergroupid character(36),
|
||||
userid character(36)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sys_usergrouprole (
|
||||
usergroupid character(36),
|
||||
roleid character(36)
|
||||
);
|
||||
|
||||
-- 幂等:先清本测试组的链,再插
|
||||
DELETE FROM sys_usergroupuser WHERE usergroupid = 'UG_TEST';
|
||||
DELETE FROM sys_usergrouprole WHERE usergroupid = 'UG_TEST';
|
||||
|
||||
-- alice 属于测试用户组 UG_TEST
|
||||
INSERT INTO sys_usergroupuser (usergroupid, userid) VALUES ('UG_TEST', 'USER_ALICE');
|
||||
|
||||
-- UG_TEST 关联 3 个受控实体角色(与 bootstrap-privilege.sql 一致)
|
||||
INSERT INTO sys_usergrouprole (usergroupid, roleid) VALUES
|
||||
('UG_TEST', 'ROLE_CUSTOMER'),
|
||||
('UG_TEST', 'ROLE_PROJECT'),
|
||||
('UG_TEST', 'ROLE_TASK');
|
||||
|
||||
-- 4. 受控实体 CREATEBY 重分区(与 bootstrap-privilege.sql §4 同口径,确定性幂等)
|
||||
WITH ranked AS (
|
||||
SELECT eip4pt_task_id, row_number() OVER (ORDER BY eip4pt_task_id) AS rn FROM eip4pt_task
|
||||
)
|
||||
UPDATE eip4pt_task t SET createby = CASE (r.rn % 3)
|
||||
WHEN 0 THEN 'USER_ALICE' WHEN 1 THEN 'USER_BOB' ELSE 'USER_CAROL' END
|
||||
FROM ranked r WHERE t.eip4pt_task_id = r.eip4pt_task_id;
|
||||
|
||||
WITH ranked AS (
|
||||
SELECT eip4pt_project_id, row_number() OVER (ORDER BY eip4pt_project_id) AS rn FROM eip4pt_project
|
||||
)
|
||||
UPDATE eip4pt_project t SET createby = CASE (r.rn % 3)
|
||||
WHEN 0 THEN 'USER_ALICE' WHEN 1 THEN 'USER_BOB' ELSE 'USER_CAROL' END
|
||||
FROM ranked r WHERE t.eip4pt_project_id = r.eip4pt_project_id;
|
||||
|
||||
WITH ranked AS (
|
||||
SELECT eip4pt_customer_id, row_number() OVER (ORDER BY eip4pt_customer_id) AS rn FROM eip4pt_customer
|
||||
)
|
||||
UPDATE eip4pt_customer t SET createby = CASE (r.rn % 3)
|
||||
WHEN 0 THEN 'USER_ALICE' WHEN 1 THEN 'USER_BOB' ELSE 'USER_CAROL' END
|
||||
FROM ranked r WHERE t.eip4pt_customer_id = r.eip4pt_customer_id;
|
||||
19
pom.xml
19
pom.xml
@@ -34,6 +34,7 @@
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<archunit.version>1.3.0</archunit.version>
|
||||
<jjwt.version>0.12.6</jjwt.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
@@ -128,6 +129,24 @@
|
||||
<version>${archunit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- P2 认证:无状态 JWT 签发/校验(jjwt 0.12.x,HS256 对称密钥) -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
</project>
|
||||
|
||||
Reference in New Issue
Block a user