feat(mcp): 服务 Token 生命周期与开放通道域绑定 (REQ-20260911-0014)
- agent_api_key 增加 principal_type/subject_name(V4 Flyway + rollback),integration.context.get 按列判定主体类型\n- Open API 支持 clients 服务密钥→作用域绑定;service ensure get-or-create/无密文轮换,旧密钥禁签 service\n- 服务 Token 吊销/轮换;人员停用后 user Token 失效(60s 本地缓存);AkAuthFilter 401 返回 UNAUTHENTICATED\n- ensure 入口约束:service 仅 sync 作用域、user 禁 sync;sync 作用域预建并绑定 integration.context.get\n- 单测 157 通过;本机 test-up 冒烟通过(跨域/旧密钥/user-sync 403,service context 自检,吊销立即 401,吊销后再签发)
This commit is contained in:
@@ -156,6 +156,12 @@ public class AdminConsoleController {
|
||||
tokenService.delete(id, adminId(session));
|
||||
}
|
||||
|
||||
/** 轮换:禁用旧把并按原主体/作用域签新把,明文仅在本次响应返回(REQ-20260911-0014)。 */
|
||||
@PostMapping("/tokens/{id}/rotate")
|
||||
public List<AdminTokenService.IssuedToken> rotateToken(@PathVariable Long id, HttpSession session) {
|
||||
return tokenService.rotate(id, adminId(session));
|
||||
}
|
||||
|
||||
@GetMapping("/tools")
|
||||
public List<ToolView> tools(@RequestParam(defaultValue = "") String category,
|
||||
@RequestParam(defaultValue = "") String kind,
|
||||
|
||||
@@ -55,23 +55,66 @@ public class AdminTokenService {
|
||||
|
||||
/** 签发一把绑定单个作用域的 Token;人员/作用域合法性由调用方保证。 */
|
||||
public IssuedToken issueSingle(Long userId, String memo, Long scopeId, Date expireTime, Long creatorId) {
|
||||
String plaintext = "xqak_" + AdminAuthController.randomHex(24);
|
||||
AgentApiKey token = new AgentApiKey();
|
||||
AgentApiKey token = newToken(memo, expireTime, creatorId);
|
||||
token.setUserId(userId);
|
||||
token.setKeyPrefix(plaintext.substring(0, 13));
|
||||
token.setKeyHash(AuthService.sha256Hex(plaintext));
|
||||
token.setKeyCipher(tokenCipher.encrypt(plaintext));
|
||||
token.setPrincipalType(AgentApiKey.PRINCIPAL_TYPE_USER);
|
||||
return insert(token, scopeId, creatorId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 签发服务 Token(principal_type=service):不绑定人员,行级权限不适用,
|
||||
* 数据范围由绑定的作用域决定(scope 粒度)。subjectName 标识服务主体,供 get-or-create 查找。
|
||||
*/
|
||||
public IssuedToken issueServiceToken(String serviceName, String memo, Long scopeId, Date expireTime, Long creatorId) {
|
||||
if (serviceName == null || !serviceName.trim().matches("[a-z][a-z0-9_-]{0,63}")) bad("服务主体标识格式无效");
|
||||
AgentApiKey token = newToken(memo, expireTime, creatorId);
|
||||
token.setPrincipalType(AgentApiKey.PRINCIPAL_TYPE_SERVICE);
|
||||
token.setSubjectName(serviceName.trim());
|
||||
return insert(token, scopeId, creatorId);
|
||||
}
|
||||
|
||||
private AgentApiKey newToken(String memo, Date expireTime, Long creatorId) {
|
||||
AgentApiKey token = new AgentApiKey();
|
||||
token.setMemo(trim(memo, 255));
|
||||
token.setStatus((byte) 1);
|
||||
token.setExpireTime(expireTime);
|
||||
token.setCreateId(creatorId);
|
||||
token.setModifyId(creatorId);
|
||||
token.setSoftDelete((byte) 0);
|
||||
return token;
|
||||
}
|
||||
|
||||
private IssuedToken insert(AgentApiKey token, Long scopeId, Long creatorId) {
|
||||
String plaintext = "xqak_" + AdminAuthController.randomHex(24);
|
||||
token.setKeyPrefix(plaintext.substring(0, 13));
|
||||
token.setKeyHash(AuthService.sha256Hex(plaintext));
|
||||
token.setKeyCipher(tokenCipher.encrypt(plaintext));
|
||||
tokenMapper.insert(token);
|
||||
replaceScopes(token.getId(), List.of(scopeId), creatorId);
|
||||
return new IssuedToken(plaintext, view(token));
|
||||
}
|
||||
|
||||
/** 轮换:禁用旧把(吊销立即生效,AkAuthFilter 校验 status),按原主体/作用域/过期时间签新把,明文逐把返回。 */
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public List<IssuedToken> rotate(Long tokenId, Long operatorId) {
|
||||
AgentApiKey current = activeToken(tokenId);
|
||||
List<Long> scopeIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
|
||||
.eq(TokenScope::getTokenId, tokenId).eq(TokenScope::getSoftDelete, 0))
|
||||
.stream().map(TokenScope::getScopeId).toList();
|
||||
if (scopeIds.isEmpty()) bad("Token 未绑定作用域,无法轮换");
|
||||
current.setStatus((byte) 0);
|
||||
current.setModifyId(operatorId);
|
||||
tokenMapper.updateById(current);
|
||||
boolean service = AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(current.getPrincipalType());
|
||||
return scopeIds.stream()
|
||||
.map(scopeId -> service
|
||||
? issueServiceToken(current.getSubjectName(), current.getMemo(), scopeId,
|
||||
current.getExpireTime(), operatorId)
|
||||
: issueSingle(current.getUserId(), current.getMemo(), scopeId,
|
||||
current.getExpireTime(), operatorId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** 查找某人员在某作用域下的有效 Token(正常状态且未过期),取最新一把;无则 null。 */
|
||||
public AgentApiKey findActiveToken(Long userId, Long scopeId) {
|
||||
List<Long> tokenIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
|
||||
@@ -90,6 +133,25 @@ public class AdminTokenService {
|
||||
.stream().findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/** 查找某服务主体在某作用域下的有效 Token(正常状态且未过期),取最新一把;无则 null。 */
|
||||
public AgentApiKey findActiveServiceToken(String serviceName, Long scopeId) {
|
||||
List<Long> tokenIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
|
||||
.eq(TokenScope::getScopeId, scopeId).eq(TokenScope::getSoftDelete, 0))
|
||||
.stream().map(TokenScope::getTokenId).toList();
|
||||
if (tokenIds.isEmpty()) return null;
|
||||
return tokenMapper.selectList(new LambdaQueryWrapper<AgentApiKey>()
|
||||
.in(AgentApiKey::getId, tokenIds)
|
||||
.eq(AgentApiKey::getPrincipalType, AgentApiKey.PRINCIPAL_TYPE_SERVICE)
|
||||
.eq(AgentApiKey::getSubjectName, serviceName)
|
||||
.eq(AgentApiKey::getStatus, 1)
|
||||
.eq(AgentApiKey::getSoftDelete, 0)
|
||||
.and(w -> w.isNull(AgentApiKey::getExpireTime)
|
||||
.or().gt(AgentApiKey::getExpireTime, new Date()))
|
||||
.orderByDesc(AgentApiKey::getCreateTime)
|
||||
.last("LIMIT 1"))
|
||||
.stream().findFirst().orElse(null);
|
||||
}
|
||||
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public void update(Long tokenId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
|
||||
AgentApiKey current = activeToken(tokenId);
|
||||
@@ -133,6 +195,7 @@ public class AdminTokenService {
|
||||
new LambdaQueryWrapper<AgentScope>().in(AgentScope::getId, scopeIds))
|
||||
.stream().map(AgentScope::getName).toList();
|
||||
return new TokenView(token.getId(), token.getKeyPrefix(), token.getMemo(), token.getStatus(),
|
||||
token.getPrincipalType(), token.getSubjectName(),
|
||||
token.getExpireTime(), token.getLastUsedTime(), scopeIds, scopeNames);
|
||||
}
|
||||
|
||||
@@ -187,7 +250,8 @@ public class AdminTokenService {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
|
||||
}
|
||||
|
||||
public record TokenView(Long id, String keyPrefix, String memo, Byte status, Date expireTime,
|
||||
public record TokenView(Long id, String keyPrefix, String memo, Byte status,
|
||||
String principalType, String subjectName, Date expireTime,
|
||||
Date lastUsedTime, List<Long> scopeIds, List<String> scopeNames) {}
|
||||
public record IssuedToken(String plaintext, TokenView token) {}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ public class AgentApiKey implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 主体类型:用户委托(绑定 user_id,行级权限跟随人员) */
|
||||
public static final String PRINCIPAL_TYPE_USER = "user";
|
||||
|
||||
/** 主体类型:租户服务(Open API 服务密钥签发,不绑定人员) */
|
||||
public static final String PRINCIPAL_TYPE_SERVICE = "service";
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@@ -33,10 +39,20 @@ public class AgentApiKey implements Serializable {
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 所属人(m0.user.id)
|
||||
* 所属人(m0.user.id);principal_type=service 时为 NULL
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 主体类型:user=用户委托 service=租户服务
|
||||
*/
|
||||
private String principalType;
|
||||
|
||||
/**
|
||||
* 服务主体标识(principal_type=service 时必填,如 xiaoqu-ai)
|
||||
*/
|
||||
private String subjectName;
|
||||
|
||||
/**
|
||||
* ak 前缀(展示用,如 xqak_abcd1234)
|
||||
*/
|
||||
|
||||
@@ -69,16 +69,13 @@ public class IntegrationContextService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主体类型判定(5629 切换点):agent_api_key 后续会新增 principal_type 列
|
||||
* (REQ-20260911-0013 的 Flyway),届时只需改本方法为读列。
|
||||
* 当前按现有数据推导:token 绑定了用户(user_id 非空且人已解析)即 user_delegated,
|
||||
* 否则 tenant_service(存量 ak 均为 ensure 签发的用户 Token,不会走到该分支)。
|
||||
*/
|
||||
/** 主体类型按 agent_api_key.principal_type 列判定(REQ-20260911-0014 切换):service → tenant_service。 */
|
||||
String resolvePrincipalType(AuthContext ctx) {
|
||||
AgentApiKey token = ctx.getToken();
|
||||
boolean hasUser = ctx.getUser() != null || (token != null && token.getUserId() != null);
|
||||
return hasUser ? PRINCIPAL_USER_DELEGATED : PRINCIPAL_TENANT_SERVICE;
|
||||
if (token != null && AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(token.getPrincipalType())) {
|
||||
return PRINCIPAL_TENANT_SERVICE;
|
||||
}
|
||||
return PRINCIPAL_USER_DELEGATED;
|
||||
}
|
||||
|
||||
/** 数据权限版本:token_scope 绑定集合的最大 modify_time(空取 create_time)转 epoch 毫秒;无绑定为 0 */
|
||||
@@ -110,11 +107,16 @@ public class IntegrationContextService {
|
||||
return scopes.stream().map(AgentScope::getCode).sorted().collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
/** 用户委托 → 用户 ID;服务主体(无人员绑定)→ token 自身 ID 作为服务主体标识 */
|
||||
private Long subjectId(AuthContext ctx) {
|
||||
if (ctx.getUser() != null) {
|
||||
return ctx.getUser().getId();
|
||||
}
|
||||
return ctx.getToken() == null ? null : ctx.getToken().getUserId();
|
||||
AgentApiKey token = ctx.getToken();
|
||||
if (token == null) {
|
||||
return null;
|
||||
}
|
||||
return token.getUserId() != null ? token.getUserId() : token.getId();
|
||||
}
|
||||
|
||||
private List<AgentScope> enabledScopes(List<TokenScope> bindings) {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package me.iiv.agent.open;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* /api/open 服务密钥配置(REQ-20260911-0014)。
|
||||
* 旧配置 api-key 为单个不绑定数据域的密钥,仅保留给存量用户 Token ensure;
|
||||
* 新接入方(尤其签发 service 类型 Token)必须配置 clients:密钥 → 名称 + 允许的作用域编码,
|
||||
* 鉴权时按密钥确定可调用的数据域,越域请求 403。
|
||||
*/
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "app.open")
|
||||
public class OpenClientProperties {
|
||||
|
||||
/** 兼容旧配置:单个静态密钥,不限作用域(视为隐式 client,name=legacy) */
|
||||
private String apiKey;
|
||||
|
||||
/** 服务密钥清单 */
|
||||
private List<Client> clients = new ArrayList<>();
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public List<Client> getClients() {
|
||||
return clients;
|
||||
}
|
||||
|
||||
public void setClients(List<Client> clients) {
|
||||
this.clients = clients;
|
||||
}
|
||||
|
||||
public static class Client {
|
||||
|
||||
/** 密钥明文(X-Open-Key 头值) */
|
||||
private String key;
|
||||
|
||||
/** 调用方名称(审计/排查用) */
|
||||
private String name;
|
||||
|
||||
/** 允许操作的作用域编码;空列表 = 未绑定数据域,不能签发/操作任何 scope */
|
||||
private List<String> scopes = new ArrayList<>();
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getScopes() {
|
||||
return scopes;
|
||||
}
|
||||
|
||||
public void setScopes(List<String> scopes) {
|
||||
this.scopes = scopes;
|
||||
}
|
||||
}
|
||||
|
||||
/** 鉴权通过的调用方;scopes 为 null 表示旧密钥(不限作用域,但不可签发 service Token) */
|
||||
public record ResolvedClient(String name, List<String> scopes, boolean legacy) {}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@@ -13,16 +12,24 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* /api/open 通道服务间鉴权:X-Open-Key 静态密钥(配置 app.open.api-key)。
|
||||
* 与 ak 体系、后台 session 体系完全分离;配置为空 = 接口关闭。
|
||||
* /api/open 通道服务间鉴权:X-Open-Key 服务密钥(配置 app.open,见 OpenClientProperties)。
|
||||
* 鉴权通过后将调用方(名称 + 绑定的作用域编码)写入请求属性 {@link #CLIENT_ATTRIBUTE},
|
||||
* 供 ensure 校验"密钥 → 数据域"绑定关系。与 ak 体系、后台 session 体系完全分离;
|
||||
* 未配置任何密钥 = 接口关闭。
|
||||
*/
|
||||
@Component
|
||||
public class OpenKeyFilter extends OncePerRequestFilter {
|
||||
|
||||
static final String OPEN_KEY_HEADER = "X-Open-Key";
|
||||
|
||||
@Value("${app.open.api-key:}")
|
||||
private String apiKey;
|
||||
/** 请求属性名:值为 OpenClientProperties.ResolvedClient */
|
||||
static final String CLIENT_ATTRIBUTE = "me.iiv.agent.open.client";
|
||||
|
||||
private final OpenClientProperties properties;
|
||||
|
||||
public OpenKeyFilter(OpenClientProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
@@ -33,19 +40,38 @@ public class OpenKeyFilter extends OncePerRequestFilter {
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (apiKey == null || apiKey.isBlank()) {
|
||||
error(response, 403, "Open API 未启用");
|
||||
return;
|
||||
}
|
||||
String provided = request.getHeader(OPEN_KEY_HEADER);
|
||||
if (provided == null || !MessageDigest.isEqual(
|
||||
apiKey.getBytes(StandardCharsets.UTF_8), provided.getBytes(StandardCharsets.UTF_8))) {
|
||||
error(response, 401, "服务间密钥无效");
|
||||
OpenClientProperties.ResolvedClient client = provided == null ? null : resolve(provided);
|
||||
if (client == null) {
|
||||
boolean configured = properties.getApiKey() != null && !properties.getApiKey().isBlank()
|
||||
|| properties.getClients() != null && !properties.getClients().isEmpty();
|
||||
error(response, configured ? 401 : 403, configured ? "服务间密钥无效" : "Open API 未启用");
|
||||
return;
|
||||
}
|
||||
request.setAttribute(CLIENT_ATTRIBUTE, client);
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/** 命中 clients 清单返回绑定的作用域;命中旧 api-key 返回不绑域的 legacy client;均未命中返回 null */
|
||||
private OpenClientProperties.ResolvedClient resolve(String provided) {
|
||||
byte[] providedBytes = provided.getBytes(StandardCharsets.UTF_8);
|
||||
if (properties.getClients() != null) {
|
||||
for (OpenClientProperties.Client client : properties.getClients()) {
|
||||
if (client.getKey() != null && !client.getKey().isBlank()
|
||||
&& MessageDigest.isEqual(client.getKey().getBytes(StandardCharsets.UTF_8), providedBytes)) {
|
||||
return new OpenClientProperties.ResolvedClient(
|
||||
client.getName(), client.getScopes(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
String legacy = properties.getApiKey();
|
||||
if (legacy != null && !legacy.isBlank()
|
||||
&& MessageDigest.isEqual(legacy.getBytes(StandardCharsets.UTF_8), providedBytes)) {
|
||||
return new OpenClientProperties.ResolvedClient("legacy", null, true);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void error(HttpServletResponse response, int status, String message) throws IOException {
|
||||
response.setStatus(status);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.iiv.agent.open;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -21,15 +22,21 @@ public class OpenTokenController {
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保某人员在某作用域下有有效 Token:存在则解密回传明文(created=false,二次获取),
|
||||
* 确保某主体在某作用域下有有效 Token:存在则解密回传明文(created=false,二次获取),
|
||||
* 不存在则自动创建永久 Token 并返回明文(created=true);历史无密文 Token 自动轮换后按创建返回。
|
||||
* 主体类型:缺省 user(按手机号/邮箱匹配人员);principalType=service 时按 serviceName 签发
|
||||
* 服务 Token(REQ-20260911-0014),要求所用服务密钥已在配置中绑定该作用域。
|
||||
*/
|
||||
@PostMapping("/token/ensure")
|
||||
public EnsureResult ensure(@RequestBody EnsureRequest body) {
|
||||
return openTokenService.ensure(body);
|
||||
public EnsureResult ensure(@RequestBody EnsureRequest body, HttpServletRequest request) {
|
||||
OpenClientProperties.ResolvedClient client =
|
||||
(OpenClientProperties.ResolvedClient) request.getAttribute(OpenKeyFilter.CLIENT_ATTRIBUTE);
|
||||
return openTokenService.ensure(body, client);
|
||||
}
|
||||
|
||||
public record EnsureRequest(String mobile, String email, String scopeCode) {}
|
||||
public record EnsureRequest(String mobile, String email, String scopeCode,
|
||||
String principalType, String serviceName) {}
|
||||
public record EnsureResult(boolean created, String token, String keyPrefix, Date expireTime,
|
||||
Long userId, String userName, String scopeCode) {}
|
||||
Long userId, String userName, String scopeCode,
|
||||
String principalType, String subjectName) {}
|
||||
}
|
||||
|
||||
@@ -19,10 +19,12 @@ import org.springframework.web.server.ResponseStatusException;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Open API:按 手机号/邮箱 + 作用域编码 确保 Token 存在(get-or-create)。
|
||||
* Open API:按 手机号/邮箱(user)或 服务主体标识(service)+ 作用域编码 确保 Token 存在(get-or-create)。
|
||||
* 存在有效 Token 时解密 key_cipher 回传明文(二次获取,2026-09-07 决策);
|
||||
* 历史数据无密文的 Token 自动轮换(禁用旧把、签发新把);
|
||||
* 不存在则自动创建永久 Token。两条路径均返回明文。
|
||||
* service 类型(REQ-20260911-0014):要求服务密钥已在配置中绑定该作用域(app.open.clients),
|
||||
* 旧版不限域密钥(app.open.api-key)不可签发服务 Token。
|
||||
*/
|
||||
@Service
|
||||
public class OpenTokenService {
|
||||
@@ -30,6 +32,8 @@ public class OpenTokenService {
|
||||
/** 系统签发(Open API 自动创建)的 createId 约定值 */
|
||||
static final long SYSTEM_CREATOR_ID = 0L;
|
||||
static final String AUDIT_TOOL = "open.token.ensure";
|
||||
/** SYNC 作用域编码:服务 Token 只能绑定该作用域,用户 Token 不能绑定(REQ-20260911-0014) */
|
||||
static final String SYNC_SCOPE_CODE = "sync";
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final AgentScopeMapper scopeMapper;
|
||||
@@ -48,10 +52,14 @@ public class OpenTokenService {
|
||||
}
|
||||
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public OpenTokenController.EnsureResult ensure(OpenTokenController.EnsureRequest body) {
|
||||
public OpenTokenController.EnsureResult ensure(OpenTokenController.EnsureRequest body,
|
||||
OpenClientProperties.ResolvedClient client) {
|
||||
long start = System.currentTimeMillis();
|
||||
if (body == null) bad(HttpStatus.BAD_REQUEST, "请求内容不能为空");
|
||||
if (!StringUtils.hasText(body.mobile()) && !StringUtils.hasText(body.email())) {
|
||||
boolean service = AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(body.principalType());
|
||||
if (service) {
|
||||
if (!StringUtils.hasText(body.serviceName())) bad(HttpStatus.BAD_REQUEST, "服务主体标识不能为空");
|
||||
} else if (!StringUtils.hasText(body.mobile()) && !StringUtils.hasText(body.email())) {
|
||||
bad(HttpStatus.BAD_REQUEST, "手机号和邮箱至少传一个");
|
||||
}
|
||||
if (!StringUtils.hasText(body.scopeCode())) bad(HttpStatus.BAD_REQUEST, "作用域编码不能为空");
|
||||
@@ -61,7 +69,34 @@ public class OpenTokenService {
|
||||
if (scope == null || !Byte.valueOf((byte) 1).equals(scope.getStatus())) {
|
||||
bad(HttpStatus.BAD_REQUEST, "作用域不存在或已停用");
|
||||
}
|
||||
checkScopeBinding(client, scope, service);
|
||||
if (service && !SYNC_SCOPE_CODE.equals(scope.getCode())) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "服务 Token 只能绑定 SYNC 作用域");
|
||||
}
|
||||
if (!service && SYNC_SCOPE_CODE.equals(scope.getCode())) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "SYNC 作用域仅允许服务 Token");
|
||||
}
|
||||
return service ? ensureService(body, scope, start) : ensureUser(body, scope, start);
|
||||
}
|
||||
|
||||
/** 密钥 → 数据域绑定校验:绑定了作用域清单的密钥只能操作清单内的 scope;service 签发不允许用旧版不限域密钥 */
|
||||
private void checkScopeBinding(OpenClientProperties.ResolvedClient client, AgentScope scope, boolean service) {
|
||||
if (client == null) {
|
||||
// OpenKeyFilter 已拦截无效密钥,走到这里说明上下文丢失,按未授权处理
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "服务间密钥无效");
|
||||
}
|
||||
if (client.scopes() != null && !client.scopes().contains(scope.getCode())) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
|
||||
"该服务密钥未绑定作用域 [" + scope.getCode() + "]");
|
||||
}
|
||||
if (service && client.legacy()) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
|
||||
"签发服务 Token 必须在 app.open.clients 中配置绑定了作用域的服务密钥");
|
||||
}
|
||||
}
|
||||
|
||||
private OpenTokenController.EnsureResult ensureUser(OpenTokenController.EnsureRequest body,
|
||||
AgentScope scope, long start) {
|
||||
User user = findUser(body.mobile(), body.email());
|
||||
if (user == null) {
|
||||
audit(null, null, body, "error", "人员不存在或非企业账号", start);
|
||||
@@ -70,17 +105,12 @@ public class OpenTokenService {
|
||||
|
||||
AgentApiKey existing = tokenService.findActiveToken(user.getId(), scope.getId());
|
||||
if (existing != null) {
|
||||
if (StringUtils.hasText(existing.getKeyCipher())) {
|
||||
String plaintext;
|
||||
try {
|
||||
plaintext = tokenCipher.decrypt(existing.getKeyCipher());
|
||||
} catch (IllegalStateException e) {
|
||||
audit(user, existing, body, "error", "Token 密文解密失败", start);
|
||||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Token 密文解密失败");
|
||||
}
|
||||
String plaintext = decryptOrNull(user, existing, body, start);
|
||||
if (plaintext != null) {
|
||||
audit(user, existing, body, "success", "已存在有效 Token,解密返回明文", start);
|
||||
return new OpenTokenController.EnsureResult(false, plaintext, existing.getKeyPrefix(),
|
||||
existing.getExpireTime(), user.getId(), user.getName(), scope.getCode());
|
||||
existing.getExpireTime(), user.getId(), user.getName(), scope.getCode(),
|
||||
AgentApiKey.PRINCIPAL_TYPE_USER, null);
|
||||
}
|
||||
// 历史数据无密文:禁用旧把并签发新把(轮换),保证总能拿到明文
|
||||
tokenService.status(existing.getId(), (byte) 0, SYSTEM_CREATOR_ID);
|
||||
@@ -93,7 +123,46 @@ public class OpenTokenService {
|
||||
created.setId(issued.token().id());
|
||||
audit(user, created, body, "success", "自动创建永久 Token", start);
|
||||
return new OpenTokenController.EnsureResult(true, issued.plaintext(), issued.token().keyPrefix(),
|
||||
null, user.getId(), user.getName(), scope.getCode());
|
||||
null, user.getId(), user.getName(), scope.getCode(), AgentApiKey.PRINCIPAL_TYPE_USER, null);
|
||||
}
|
||||
|
||||
private OpenTokenController.EnsureResult ensureService(OpenTokenController.EnsureRequest body,
|
||||
AgentScope scope, long start) {
|
||||
String serviceName = body.serviceName().trim();
|
||||
AgentApiKey existing = tokenService.findActiveServiceToken(serviceName, scope.getId());
|
||||
if (existing != null) {
|
||||
String plaintext = decryptOrNull(null, existing, body, start);
|
||||
if (plaintext != null) {
|
||||
audit(null, existing, body, "success", "已存在有效服务 Token,解密返回明文", start);
|
||||
return new OpenTokenController.EnsureResult(false, plaintext, existing.getKeyPrefix(),
|
||||
existing.getExpireTime(), null, null, scope.getCode(),
|
||||
AgentApiKey.PRINCIPAL_TYPE_SERVICE, serviceName);
|
||||
}
|
||||
tokenService.status(existing.getId(), (byte) 0, SYSTEM_CREATOR_ID);
|
||||
audit(null, existing, body, "success", "旧服务 Token 无密文,自动轮换", start);
|
||||
}
|
||||
|
||||
AdminTokenService.IssuedToken issued = tokenService.issueServiceToken(serviceName,
|
||||
"open-api 服务签发(" + scope.getCode() + ")", scope.getId(), null, SYSTEM_CREATOR_ID);
|
||||
AgentApiKey created = new AgentApiKey();
|
||||
created.setId(issued.token().id());
|
||||
audit(null, created, body, "success", "自动创建服务 Token", start);
|
||||
return new OpenTokenController.EnsureResult(true, issued.plaintext(), issued.token().keyPrefix(),
|
||||
null, null, null, scope.getCode(), AgentApiKey.PRINCIPAL_TYPE_SERVICE, serviceName);
|
||||
}
|
||||
|
||||
/** 已有 Token 解密回明文;无密文返回 null(调用方走轮换);解密失败 500 不回退 */
|
||||
private String decryptOrNull(User user, AgentApiKey existing, OpenTokenController.EnsureRequest body,
|
||||
long start) {
|
||||
if (!StringUtils.hasText(existing.getKeyCipher())) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return tokenCipher.decrypt(existing.getKeyCipher());
|
||||
} catch (IllegalStateException e) {
|
||||
audit(user, existing, body, "error", "Token 密文解密失败", start);
|
||||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Token 密文解密失败");
|
||||
}
|
||||
}
|
||||
|
||||
/** 手机号优先、邮箱兜底;只认企业账号(enterprise_type 0/1,历史 NULL 保留),与后台用户列表同口径。 */
|
||||
@@ -113,7 +182,9 @@ public class OpenTokenService {
|
||||
private void audit(User user, AgentApiKey token, OpenTokenController.EnsureRequest body,
|
||||
String status, String message, long start) {
|
||||
String digest = "mobile=" + maskMobile(body.mobile()) + " email=" + maskEmail(body.email())
|
||||
+ " scopeCode=" + body.scopeCode();
|
||||
+ " scopeCode=" + body.scopeCode()
|
||||
+ (body.principalType() == null ? "" : " principalType=" + body.principalType())
|
||||
+ (body.serviceName() == null ? "" : " serviceName=" + body.serviceName());
|
||||
auditService.record(new AuthContext(token, user), AUDIT_TOOL, digest,
|
||||
status, message, System.currentTimeMillis() - start);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,8 @@ public class AkAuthFilter extends OncePerRequestFilter {
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("error", "unauthorized");
|
||||
body.put("message", "缺少有效的 Authorization: Bearer <ak>,或 ak 已禁用/过期");
|
||||
body.put("code", "UNAUTHENTICATED");
|
||||
body.put("message", "缺少有效的 Authorization: Bearer <ak>,或 ak 已禁用/过期/人员已停用");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(body));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,14 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* ak 解析:ak → SHA-256 → agent_api_key → 人(Redis 热缓存优先,回源 m0.user)。
|
||||
* ak 解析:ak → SHA-256 → agent_api_key → 人(本地短 TTL 缓存 → Redis 热缓存 → m0.user)。
|
||||
* principal_type=service 的 Token 不绑定人员,跳过人员状态检查。
|
||||
* user 类型 Token 每次解析都校验人员在职状态(soft_delete=0 有效),
|
||||
* 人员状态本地缓存 60s(REQ-20260911-0014),停用最长 60s 后生效,避免每请求查 m0 库。
|
||||
*/
|
||||
@Component
|
||||
public class AuthService {
|
||||
@@ -28,10 +33,16 @@ public class AuthService {
|
||||
/** 老系统写入的用户热缓存 key 前缀(fastjson camelCase JSON) */
|
||||
private static final String USER_CACHE_KEY = "entity:User:";
|
||||
|
||||
/** 人员状态本地缓存 TTL(毫秒):停用/换绑最长 60s 后对 ak 调用生效 */
|
||||
private static final long USER_CACHE_TTL_MS = 60_000L;
|
||||
|
||||
final AgentApiKeyMapper agentApiKeyMapper;
|
||||
final UserMapper userMapper;
|
||||
final StringRedisTemplate redisTemplate;
|
||||
|
||||
/** userId → 人员快照(含不存在=null 的负缓存),按 TTL 过期 */
|
||||
private final Map<Long, CachedUser> userCache = new ConcurrentHashMap<>();
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
@@ -42,7 +53,7 @@ public class AuthService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 ak,返回 AuthContext;ak 无效/禁用/过期或人不存在时返回 null。
|
||||
* 解析 ak,返回 AuthContext;ak 无效/禁用/过期、人员不存在/已停用(仅 user 类型)时返回 null。
|
||||
*/
|
||||
public AuthContext resolve(String ak) {
|
||||
AgentApiKey token = agentApiKeyMapper.selectOne(new LambdaQueryWrapper<AgentApiKey>()
|
||||
@@ -54,9 +65,12 @@ public class AuthService {
|
||||
if (token.getExpireTime() != null && token.getExpireTime().before(new Date())) {
|
||||
return null;
|
||||
}
|
||||
User user = loadUser(token.getUserId());
|
||||
if (user == null || (user.getSoftDelete() != null && user.getSoftDelete() == 1)) {
|
||||
return null;
|
||||
User user = null;
|
||||
if (!AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(token.getPrincipalType())) {
|
||||
user = loadUserCached(token.getUserId());
|
||||
if (user == null || (user.getSoftDelete() != null && user.getSoftDelete() == 1)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// 更新最后使用时间(自有库,读写)
|
||||
AgentApiKey update = new AgentApiKey();
|
||||
@@ -66,6 +80,21 @@ public class AuthService {
|
||||
return new AuthContext(token, user);
|
||||
}
|
||||
|
||||
/** 人员快照优先读本地缓存(TTL 60s),未命中回源 Redis 热缓存 / m0.user;不存在也缓存,防止穿透 */
|
||||
private User loadUserCached(Long userId) {
|
||||
if (userId == null) {
|
||||
return null;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
CachedUser cached = userCache.get(userId);
|
||||
if (cached != null && cached.expiresAt() > now) {
|
||||
return cached.user();
|
||||
}
|
||||
User user = loadUser(userId);
|
||||
userCache.put(userId, new CachedUser(user, now + USER_CACHE_TTL_MS));
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 用户资料优先读 Redis db5 entity:User:{id} 热缓存(变更即时生效),读不到回源 m0.user */
|
||||
private User loadUser(Long userId) {
|
||||
try {
|
||||
@@ -79,6 +108,8 @@ public class AuthService {
|
||||
return userMapper.selectById(userId);
|
||||
}
|
||||
|
||||
private record CachedUser(User user, long expiresAt) {}
|
||||
|
||||
public static String sha256Hex(String raw) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
|
||||
Reference in New Issue
Block a user