Browse Source
- 新增 McpAuthInterceptor,支持 Bearer JWT 与人员密钥两种鉴权方式 - 定义 McpAuthService、McpAccountProvider 等 SPI 契约,由应用侧实现 - 新增 McpWebMvcConfig 自动注册拦截器,未实现 SPI 时 fail-closed 返回 401 - 新增 SysUserSecret 实体及完整 CRUD,支持密钥签发、轮换、启停 - 实现凭证校验逻辑:keyId 定位、状态与有效期检查、SHA-256 摘要比对、手机号绑定校验 - 为 McpStreamableController 和 McpToolConfig 添加 apelet.mcp.enabled 开关控制 - 非管理员只能查看和操作自己的密钥,响应中不返回 secretHash 并脱敏手机号feature/2026-10/1031-ccc-dev
27 changed files with 1172 additions and 667 deletions
@ -1,262 +0,0 @@
@@ -1,262 +0,0 @@
|
||||
package apelet.tenantadmin.interceptor; |
||||
|
||||
import apelet.common.core.constant.AppDeviceType; |
||||
import apelet.common.core.constant.ApplicationConstant; |
||||
import apelet.common.core.constant.ErrorCodeEnum; |
||||
import apelet.common.core.object.ResponseResult; |
||||
import apelet.common.core.object.TokenData; |
||||
import apelet.common.core.util.JwtUtil; |
||||
import apelet.common.core.util.RedisKeyUtil; |
||||
import apelet.common.openapi.model.OpenApiApp; |
||||
import apelet.common.openapi.service.OpenApiAppService; |
||||
import apelet.tenantadmin.config.ApplicationConfig; |
||||
import apelet.tenantadmin.upms.model.SysUser; |
||||
import apelet.tenantadmin.upms.model.SysUserSecret; |
||||
import apelet.tenantadmin.upms.service.SysUserSecretService; |
||||
import apelet.tenantadmin.upms.service.SysUserService; |
||||
import apelet.tenantadmin.upms.service.UserSessionContextService; |
||||
import cn.hutool.core.util.StrUtil; |
||||
import com.alibaba.fastjson.JSON; |
||||
import io.jsonwebtoken.Claims; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.redisson.api.RBucket; |
||||
import org.redisson.api.RedissonClient; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.stereotype.Component; |
||||
import org.springframework.web.context.request.RequestContextHolder; |
||||
import org.springframework.web.context.request.ServletRequestAttributes; |
||||
import org.springframework.web.servlet.HandlerInterceptor; |
||||
|
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletRequestWrapper; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
import java.io.IOException; |
||||
import java.io.PrintWriter; |
||||
import java.util.concurrent.TimeUnit; |
||||
|
||||
/** |
||||
* MCP 端点({@code /tenantadmin/mcp})的鉴权拦截器。 |
||||
* <p>支持两种调用方身份,按顺序判定:</p> |
||||
* <ol> |
||||
* <li>{@code Authorization: Bearer <jwt>} —— 登录态,兼容现有调用方;</li> |
||||
* <li>{@code X-Mcp-User} + {@code X-Mcp-Secret} —— 人员级密钥,格式为 "keyId.secret",锁定到具体账号。</li> |
||||
* </ol> |
||||
* <p>两者都带时以 Bearer 优先,避免调用方主动降级到密钥分支。</p> |
||||
* <p>校验通过后统一注入 {@link TokenData},下游(在线表单、数据权限、流程)对来源无感知。</p> |
||||
* <p><b>注意</b>:本拦截器注册后,{@code /tenantadmin/mcp} 已从 AuthenticationInterceptor 的路径中排除, |
||||
* 因此 MCP 路径不做"菜单×URL"越权校验;数据权限(DATA_PERM)仍照常生效。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Slf4j |
||||
@Component |
||||
public class McpAuthInterceptor implements HandlerInterceptor { |
||||
|
||||
/** |
||||
* MCP 端点路径。注意该路径硬编码在 common-core 的 McpStreamableController 上,两边需保持一致。 |
||||
*/ |
||||
public static final String MCP_ENDPOINT_PATH = "/tenantadmin/mcp"; |
||||
|
||||
/** |
||||
* 人员手机号请求头。 |
||||
*/ |
||||
public static final String HEADER_MCP_USER = "X-Mcp-User"; |
||||
/** |
||||
* 人员密钥请求头,值为 "keyId.secret"。 |
||||
*/ |
||||
public static final String HEADER_MCP_SECRET = "X-Mcp-Secret"; |
||||
|
||||
/** |
||||
* 会话复用缓存前缀:一个账号在 TTL 内复用同一个会话,避免每个请求都重建会话上下文(含查库与多次Redis写入)。 |
||||
*/ |
||||
private static final String MCP_SESSION_KEY_PREFIX = "MCP_SESSION:"; |
||||
/** |
||||
* 会话复用TTL(秒)。刻意短于会话本身的有效期,以限制角色/数据权限变更后的缓存陈旧窗口。 |
||||
*/ |
||||
private static final long MCP_SESSION_TTL_SECONDS = 1800L; |
||||
/** |
||||
* JWT 中承载会话Id的 claim 名称,需与登录链路保持一致。 |
||||
*/ |
||||
private static final String CLAIM_SESSION_ID = "sessionId"; |
||||
|
||||
@Autowired |
||||
private ApplicationConfig appConfig; |
||||
@Autowired |
||||
private RedissonClient redissonClient; |
||||
@Autowired |
||||
private SysUserSecretService sysUserSecretService; |
||||
@Autowired |
||||
private SysUserService sysUserService; |
||||
@Autowired |
||||
private OpenApiAppService openApiAppService; |
||||
@Autowired |
||||
private UserSessionContextService userSessionContextService; |
||||
|
||||
@Override |
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { |
||||
String authorization = request.getHeader(appConfig.getTokenHeaderKey()); |
||||
TokenData tokenData = null; |
||||
if (StrUtil.isNotBlank(authorization)) { |
||||
tokenData = this.authenticateByJwt(authorization); |
||||
if (tokenData == null) { |
||||
this.outputUnauthorized(response, "登录会话已过期或尚未登录,请重新登录!"); |
||||
return false; |
||||
} |
||||
} else { |
||||
String mobile = request.getHeader(HEADER_MCP_USER); |
||||
String credential = request.getHeader(HEADER_MCP_SECRET); |
||||
if (StrUtil.isBlank(mobile) && StrUtil.isBlank(credential)) { |
||||
this.outputUnauthorized(response, "缺少调用凭证,请提供 Authorization 或人员密钥!"); |
||||
return false; |
||||
} |
||||
ResponseResult<SysUserSecret> authResult = sysUserSecretService.authenticate(mobile, credential); |
||||
if (!authResult.isSuccess()) { |
||||
log.warn("MCP 密钥鉴权失败,keyId={}, mobile={}, 原因={}", this.maskKeyId(credential), mobile, authResult.getErrorMessage()); |
||||
this.outputUnauthorized(response, authResult.getErrorMessage()); |
||||
return false; |
||||
} |
||||
SysUser user = sysUserService.getById(authResult.getData().getUserId()); |
||||
if (user == null) { |
||||
this.outputUnauthorized(response, "凭证无效!"); |
||||
return false; |
||||
} |
||||
tokenData = this.resolveKeyBranchTokenData(user, authResult.getData()); |
||||
} |
||||
TokenData.addToRequest(tokenData); |
||||
// 在线表单引擎需要 MenuId 头来选取数据权限规则分支;MCP 无菜单上下文,统一按"通用规则"处理。
|
||||
this.wrapRequestWithMenuId(request); |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* 校验登录态 JWT 并取回会话中的 TokenData。口径与 AuthenticationInterceptor 保持一致。 |
||||
* |
||||
* @param token 请求头中的 JWT(含 Bearer 前缀)。 |
||||
* @return 校验通过返回 TokenData,否则返回null。 |
||||
*/ |
||||
private TokenData authenticateByJwt(String token) { |
||||
Claims claims = JwtUtil.parseToken(token, appConfig.getTokenSigningKey()); |
||||
if (JwtUtil.isNullOrExpired(claims)) { |
||||
return null; |
||||
} |
||||
String sessionId = (String) claims.get(CLAIM_SESSION_ID); |
||||
if (StrUtil.isBlank(sessionId)) { |
||||
return null; |
||||
} |
||||
RBucket<String> sessionData = redissonClient.getBucket(RedisKeyUtil.makeSessionIdKey(sessionId)); |
||||
if (!sessionData.isExists()) { |
||||
return null; |
||||
} |
||||
TokenData tokenData = JSON.parseObject(sessionData.get(), TokenData.class); |
||||
if (tokenData != null) { |
||||
tokenData.setToken(token); |
||||
} |
||||
return tokenData; |
||||
} |
||||
|
||||
/** |
||||
* 解决密钥分支的 TokenData:优先复用该账号已有的 MCP 会话,避免每个请求都重建会话上下文。 |
||||
* |
||||
* @param user 密钥绑定的账号。 |
||||
* @param userSecret 已通过校验的密钥记录。 |
||||
* @return 可直接注入请求上下文的 TokenData。 |
||||
*/ |
||||
private TokenData resolveKeyBranchTokenData(SysUser user, SysUserSecret userSecret) { |
||||
RBucket<String> sessionIdBucket = redissonClient.getBucket(MCP_SESSION_KEY_PREFIX + user.getUserId()); |
||||
String sessionId = sessionIdBucket.get(); |
||||
if (StrUtil.isNotBlank(sessionId)) { |
||||
RBucket<String> sessionData = redissonClient.getBucket(RedisKeyUtil.makeSessionIdKey(sessionId)); |
||||
if (sessionData.isExists()) { |
||||
TokenData cached = JSON.parseObject(sessionData.get(), TokenData.class); |
||||
if (cached != null) { |
||||
return cached; |
||||
} |
||||
} |
||||
} |
||||
String appCode = this.resolveAppCode(userSecret.getAppId()); |
||||
String newSessionId = userSessionContextService.generateSessionId(user.getLoginName(), AppDeviceType.WEB); |
||||
TokenData tokenData = userSessionContextService.buildTokenData(user, newSessionId, AppDeviceType.WEB, appCode); |
||||
userSessionContextService.putSessionContext(tokenData, user); |
||||
sessionIdBucket.set(newSessionId, MCP_SESSION_TTL_SECONDS, TimeUnit.SECONDS); |
||||
return tokenData; |
||||
} |
||||
|
||||
/** |
||||
* 由密钥绑定的应用Id取回应用编码,供下游的开放接口授权校验使用。 |
||||
* |
||||
* @param appId 应用Id。 |
||||
* @return 应用编码;应用不存在或已停用时返回null,由下游给出"无权调用"的可读错误。 |
||||
*/ |
||||
private String resolveAppCode(Long appId) { |
||||
if (appId == null) { |
||||
return null; |
||||
} |
||||
OpenApiApp app = openApiAppService.getById(appId); |
||||
if (app == null || app.getStatus() == null || app.getStatus() != 1) { |
||||
log.warn("MCP 密钥绑定的应用不存在或已停用,appId={}", appId); |
||||
return null; |
||||
} |
||||
return app.getAppCode(); |
||||
} |
||||
|
||||
/** |
||||
* 用 HttpServletRequestWrapper 覆盖 MenuId 请求头。 |
||||
* <p>拦截器无法修改已传入的 request 对象,只能包装后替换 RequestContextHolder 中的引用, |
||||
* 使下游通过 ContextUtil.getHttpRequest().getHeader("MenuId") 能取到值。</p> |
||||
* |
||||
* @param request 当前请求。 |
||||
*/ |
||||
private void wrapRequestWithMenuId(HttpServletRequest request) { |
||||
if (StrUtil.isNotBlank(request.getHeader(ApplicationConstant.HTTP_HEADER_MENU_ID))) { |
||||
return; |
||||
} |
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); |
||||
if (attributes == null) { |
||||
return; |
||||
} |
||||
RequestContextHolder.setRequestAttributes( |
||||
new ServletRequestAttributes(new MenuIdHeaderRequestWrapper(request), attributes.getResponse())); |
||||
} |
||||
|
||||
/** |
||||
* 仅覆盖 MenuId 请求头,其余行为全部委托给原请求(含 attribute 读写,TokenData 依赖它)。 |
||||
*/ |
||||
private static class MenuIdHeaderRequestWrapper extends HttpServletRequestWrapper { |
||||
|
||||
MenuIdHeaderRequestWrapper(HttpServletRequest request) { |
||||
super(request); |
||||
} |
||||
|
||||
@Override |
||||
public String getHeader(String name) { |
||||
if (ApplicationConstant.HTTP_HEADER_MENU_ID.equalsIgnoreCase(name)) { |
||||
return ApplicationConstant.DATA_PERM_ALL_MENU_ID; |
||||
} |
||||
return super.getHeader(name); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 日志中只保留 keyId,避免密钥口令落入日志。 |
||||
* |
||||
* @param credential 完整凭证(keyId.secret)。 |
||||
* @return 仅含 keyId 的字符串。 |
||||
*/ |
||||
private String maskKeyId(String credential) { |
||||
if (StrUtil.isBlank(credential)) { |
||||
return ""; |
||||
} |
||||
return StrUtil.subBefore(credential, SysUserSecretService.CREDENTIAL_SEPARATOR, false); |
||||
} |
||||
|
||||
private void outputUnauthorized(HttpServletResponse response, String message) throws IOException { |
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
||||
response.setHeader("WWW-Authenticate", "Bearer"); |
||||
response.setContentType("application/json; charset=utf-8"); |
||||
PrintWriter out = response.getWriter(); |
||||
out.print(JSON.toJSONString(ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED_LOGIN, message))); |
||||
out.flush(); |
||||
out.close(); |
||||
} |
||||
} |
||||
@ -0,0 +1,67 @@
@@ -0,0 +1,67 @@
|
||||
package apelet.tenantadmin.mcp; |
||||
|
||||
import apelet.common.core.mcp.auth.spi.McpAccountInfo; |
||||
import apelet.common.core.mcp.auth.spi.McpAccountProvider; |
||||
import apelet.tenantadmin.upms.model.SysUser; |
||||
import apelet.tenantadmin.upms.model.constant.SysUserStatus; |
||||
import apelet.tenantadmin.upms.model.constant.SysUserType; |
||||
import apelet.tenantadmin.upms.service.SysUserService; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
import java.util.Collection; |
||||
import java.util.Collections; |
||||
import java.util.List; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* MCP 账号信息查询 SPI 的租户端实现。 |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Service("mcpAccountProvider") |
||||
public class TenantMcpAccountProviderImpl implements McpAccountProvider { |
||||
|
||||
@Autowired |
||||
private SysUserService sysUserService; |
||||
|
||||
@Override |
||||
public McpAccountInfo getById(Long userId) { |
||||
if (userId == null) { |
||||
return null; |
||||
} |
||||
return this.convert(sysUserService.getById(userId)); |
||||
} |
||||
|
||||
@Override |
||||
public List<McpAccountInfo> listByIds(Collection<Long> userIds) { |
||||
if (userIds == null || userIds.isEmpty()) { |
||||
return Collections.emptyList(); |
||||
} |
||||
return sysUserService.listByIds(userIds).stream().map(this::convert).collect(Collectors.toList()); |
||||
} |
||||
|
||||
/** |
||||
* 把应用侧的账号模型折算成 core 侧的账号信息。 |
||||
* |
||||
* @param user 账号对象。 |
||||
* @return 账号信息;入参为null时返回null。 |
||||
*/ |
||||
private McpAccountInfo convert(SysUser user) { |
||||
if (user == null) { |
||||
return null; |
||||
} |
||||
McpAccountInfo info = new McpAccountInfo(); |
||||
info.setUserId(user.getUserId()); |
||||
info.setLoginName(user.getLoginName()); |
||||
info.setShowName(user.getShowName()); |
||||
info.setDeptId(user.getDeptId()); |
||||
info.setMobile(user.getMobile()); |
||||
info.setHeadImageUrl(user.getHeadImageUrl()); |
||||
// 用户类型/状态枚举属应用侧概念,在这里折算成布尔值交给 core。
|
||||
info.setIsAdmin(user.getUserType() != null && user.getUserType() == SysUserType.TYPE_ADMIN); |
||||
info.setEnabled(user.getUserStatus() == null || user.getUserStatus() != SysUserStatus.STATUS_LOCKED); |
||||
return info; |
||||
} |
||||
} |
||||
@ -0,0 +1,106 @@
@@ -0,0 +1,106 @@
|
||||
package apelet.tenantadmin.mcp; |
||||
|
||||
import apelet.common.core.constant.AppDeviceType; |
||||
import apelet.common.core.mcp.auth.session.UserSessionContextService; |
||||
import apelet.common.core.mcp.auth.spi.McpAuthResult; |
||||
import apelet.common.core.mcp.auth.spi.McpAuthService; |
||||
import apelet.common.core.object.ResponseResult; |
||||
import apelet.common.core.object.TokenData; |
||||
import apelet.common.core.util.JwtUtil; |
||||
import apelet.common.core.util.RedisKeyUtil; |
||||
import apelet.common.openapi.model.OpenApiApp; |
||||
import apelet.common.openapi.model.SysUserSecret; |
||||
import apelet.common.openapi.service.OpenApiAppService; |
||||
import apelet.common.openapi.service.SysUserSecretService; |
||||
import apelet.tenantadmin.config.ApplicationConfig; |
||||
import cn.hutool.core.util.StrUtil; |
||||
import com.alibaba.fastjson.JSON; |
||||
import io.jsonwebtoken.Claims; |
||||
import org.redisson.api.RBucket; |
||||
import org.redisson.api.RedissonClient; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
/** |
||||
* MCP 鉴权 SPI 的租户端实现。 |
||||
* <p>两条分支的落点一致:都产出一份 {@code TokenData},由拦截器注入请求上下文,下游无感知。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Service("mcpAuthService") |
||||
public class TenantMcpAuthServiceImpl implements McpAuthService { |
||||
|
||||
private static final int APP_STATUS_ENABLED = 1; |
||||
/** |
||||
* JWT 中承载会话Id的 claim 名称,需与登录链路保持一致。 |
||||
*/ |
||||
private static final String CLAIM_SESSION_ID = "sessionId"; |
||||
|
||||
@Autowired |
||||
private ApplicationConfig appConfig; |
||||
@Autowired |
||||
private RedissonClient redissonClient; |
||||
@Autowired |
||||
private SysUserSecretService sysUserSecretService; |
||||
@Autowired |
||||
private OpenApiAppService openApiAppService; |
||||
@Autowired |
||||
private UserSessionContextService userSessionContextService; |
||||
|
||||
@Override |
||||
public String getBearerHeaderName() { |
||||
return appConfig.getTokenHeaderKey(); |
||||
} |
||||
|
||||
@Override |
||||
public McpAuthResult authenticateByJwt(String token) { |
||||
Claims claims = JwtUtil.parseToken(token, appConfig.getTokenSigningKey()); |
||||
if (JwtUtil.isNullOrExpired(claims)) { |
||||
return McpAuthResult.fail("登录会话已过期或尚未登录,请重新登录!"); |
||||
} |
||||
String sessionId = (String) claims.get(CLAIM_SESSION_ID); |
||||
if (StrUtil.isBlank(sessionId)) { |
||||
return McpAuthResult.fail("登录会话无效,请重新登录!"); |
||||
} |
||||
RBucket<String> sessionData = redissonClient.getBucket(RedisKeyUtil.makeSessionIdKey(sessionId)); |
||||
if (!sessionData.isExists()) { |
||||
return McpAuthResult.fail("登录会话已失效,请重新登录!"); |
||||
} |
||||
TokenData tokenData = JSON.parseObject(sessionData.get(), TokenData.class); |
||||
if (tokenData == null) { |
||||
return McpAuthResult.fail("登录会话已失效,请重新登录!"); |
||||
} |
||||
tokenData.setToken(token); |
||||
return McpAuthResult.ok(tokenData); |
||||
} |
||||
|
||||
@Override |
||||
public McpAuthResult authenticateByUserSecret(String mobile, String credential) { |
||||
ResponseResult<SysUserSecret> authResult = sysUserSecretService.authenticate(mobile, credential); |
||||
if (!authResult.isSuccess() || authResult.getData() == null) { |
||||
return McpAuthResult.fail(authResult.getErrorMessage()); |
||||
} |
||||
SysUserSecret userSecret = authResult.getData(); |
||||
String appCode = this.resolveAppCode(userSecret.getAppId()); |
||||
TokenData tokenData = userSessionContextService.buildAndCacheSession(userSecret.getUserId(), appCode, AppDeviceType.WEB); |
||||
return McpAuthResult.ok(tokenData, userSecret.getKeyId()); |
||||
} |
||||
|
||||
/** |
||||
* 由密钥绑定的应用Id取回应用编码,供下游的开放接口授权校验使用。 |
||||
* |
||||
* @param appId 应用Id。 |
||||
* @return 应用编码;应用不存在或已停用时返回null,由下游给出"无权调用"的可读错误。 |
||||
*/ |
||||
private String resolveAppCode(Long appId) { |
||||
if (appId == null) { |
||||
return null; |
||||
} |
||||
OpenApiApp app = openApiAppService.getById(appId); |
||||
if (app == null || app.getStatus() == null || app.getStatus() != APP_STATUS_ENABLED) { |
||||
return null; |
||||
} |
||||
return app.getAppCode(); |
||||
} |
||||
} |
||||
@ -1,171 +0,0 @@
@@ -1,171 +0,0 @@
|
||||
package apelet.tenantadmin.upms.controller; |
||||
|
||||
import apelet.common.core.annotation.MyRequestBody; |
||||
import apelet.common.core.constant.ErrorCodeEnum; |
||||
import apelet.common.core.object.MyOrderParam; |
||||
import apelet.common.core.object.MyPageData; |
||||
import apelet.common.core.object.MyPageParam; |
||||
import apelet.common.core.object.ResponseResult; |
||||
import apelet.common.core.util.MyCommonUtil; |
||||
import apelet.common.core.util.MyPageUtil; |
||||
import apelet.common.log.annotation.OperationLog; |
||||
import apelet.common.log.model.constant.SysOperationLogType; |
||||
import apelet.tenantadmin.upms.model.SysUserSecret; |
||||
import apelet.tenantadmin.upms.model.constant.SysUserSecretStatus; |
||||
import apelet.tenantadmin.upms.service.SysUserSecretService; |
||||
import apelet.tenantadmin.upms.vo.SysUserSecretIssueVo; |
||||
import cn.hutool.core.date.DateUtil; |
||||
import cn.hutool.core.util.StrUtil; |
||||
import com.github.pagehelper.Page; |
||||
import com.github.pagehelper.page.PageMethod; |
||||
import io.swagger.v3.oas.annotations.tags.Tag; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.web.bind.annotation.PostMapping; |
||||
import org.springframework.web.bind.annotation.RequestMapping; |
||||
import org.springframework.web.bind.annotation.RestController; |
||||
|
||||
import java.util.Date; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 用户对外密钥管理接口。 |
||||
* <p>密钥是"一人一把、锁定到具体账号"的长期凭证,签发与停用属于提权操作, |
||||
* 接口本身依赖登录态 + URL 权限控制,仅管理员角色应被授予。</p> |
||||
* <p>响应中永远不返回 secretHash;明文 secret 只在签发/轮换的响应里出现一次, |
||||
* 且对应操作日志显式关闭了响应体记录(saveResponse=false),避免明文密钥落到日志。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Tag(name = "对外密钥管理") |
||||
@Slf4j |
||||
@RestController |
||||
@RequestMapping("/tenantadmin/upms/sysUserSecret") |
||||
public class SysUserSecretController { |
||||
|
||||
@Autowired |
||||
private SysUserSecretService sysUserSecretService; |
||||
|
||||
/** |
||||
* 对外密钥分页列表。 |
||||
* |
||||
* @param sysUserSecretFilter 过滤条件(支持 loginName/mobile 模糊、userId/appId/status 精确)。 |
||||
* @param orderParam 排序参数。 |
||||
* @param pageParam 分页参数。 |
||||
* @return 应答结果对象,包含分页后的密钥列表。 |
||||
*/ |
||||
@PostMapping("/list") |
||||
public ResponseResult<MyPageData<SysUserSecret>> list( |
||||
@MyRequestBody SysUserSecret sysUserSecretFilter, |
||||
@MyRequestBody MyOrderParam orderParam, |
||||
@MyRequestBody MyPageParam pageParam) { |
||||
if (pageParam != null) { |
||||
PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); |
||||
} |
||||
String orderBy = MyOrderParam.buildOrderBy(orderParam, SysUserSecret.class); |
||||
List<SysUserSecret> secretList = sysUserSecretService.getSysUserSecretList(sysUserSecretFilter, orderBy); |
||||
long totalCount = 0L; |
||||
if (secretList instanceof Page) { |
||||
totalCount = ((Page<SysUserSecret>) secretList).getTotal(); |
||||
} |
||||
secretList.forEach(this::maskForResponse); |
||||
return ResponseResult.success(MyPageUtil.makeResponseData(secretList, totalCount)); |
||||
} |
||||
|
||||
/** |
||||
* 查看指定密钥的详情。不返回 secretHash。 |
||||
* |
||||
* @param userSecretId 密钥记录主键Id。 |
||||
* @return 应答结果对象,包含密钥详情。 |
||||
*/ |
||||
@PostMapping("/view") |
||||
public ResponseResult<SysUserSecret> view(@MyRequestBody Long userSecretId) { |
||||
if (MyCommonUtil.existBlankArgument(userSecretId)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
SysUserSecret userSecret = sysUserSecretService.getById(userSecretId); |
||||
if (userSecret == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
this.maskForResponse(userSecret); |
||||
return ResponseResult.success(userSecret); |
||||
} |
||||
|
||||
/** |
||||
* 为指定账号签发一把对外密钥。明文只在本响应中出现一次,之后无法再查。 |
||||
* |
||||
* @param userId 绑定的账号Id。 |
||||
* @param appId 绑定的OpenAPI应用Id(决定该密钥可调用的开放接口范围)。 |
||||
* @param expireTime 过期时间字符串,留空表示永不过期。 |
||||
* @return 应答结果对象,包含 keyId、明文 secret 与完整凭证。 |
||||
*/ |
||||
@OperationLog(type = SysOperationLogType.ADD, saveResponse = false) |
||||
@PostMapping("/issue") |
||||
public ResponseResult<SysUserSecretIssueVo> issue( |
||||
@MyRequestBody Long userId, |
||||
@MyRequestBody Long appId, |
||||
@MyRequestBody String expireTime) { |
||||
if (MyCommonUtil.existBlankArgument(userId, appId)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
Date expireDate = null; |
||||
if (StrUtil.isNotBlank(expireTime)) { |
||||
expireDate = DateUtil.parse(expireTime); |
||||
} |
||||
return ResponseResult.success(sysUserSecretService.issue(userId, appId, expireDate)); |
||||
} |
||||
|
||||
/** |
||||
* 轮换指定密钥的口令:keyId 不变,旧 secret 立即失效。明文只在本响应中出现一次。 |
||||
* |
||||
* @param userSecretId 密钥记录主键Id。 |
||||
* @return 应答结果对象,包含新的明文 secret 与完整凭证。 |
||||
*/ |
||||
@OperationLog(type = SysOperationLogType.UPDATE, saveResponse = false) |
||||
@PostMapping("/resetSecret") |
||||
public ResponseResult<SysUserSecretIssueVo> resetSecret(@MyRequestBody Long userSecretId) { |
||||
if (MyCommonUtil.existBlankArgument(userSecretId)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
SysUserSecretIssueVo issueVo = sysUserSecretService.resetSecret(userSecretId); |
||||
if (issueVo == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
return ResponseResult.success(issueVo); |
||||
} |
||||
|
||||
/** |
||||
* 启用/停用指定密钥。停用后该密钥的调用一律拒绝。 |
||||
* |
||||
* @param userSecretId 密钥记录主键Id。 |
||||
* @param status 目标状态(1: 启用 0: 停用)。 |
||||
* @return 应答结果对象。 |
||||
*/ |
||||
@OperationLog(type = SysOperationLogType.UPDATE, saveResponse = false) |
||||
@PostMapping("/updateStatus") |
||||
public ResponseResult<Void> updateStatus(@MyRequestBody Long userSecretId, @MyRequestBody Integer status) { |
||||
if (MyCommonUtil.existBlankArgument(userSecretId, status)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
if (!SysUserSecretStatus.isValid(status)) { |
||||
return ResponseResult.error(ErrorCodeEnum.INVALID_STATUS_ARGUMENT); |
||||
} |
||||
if (!sysUserSecretService.updateStatus(userSecretId, status)) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
return ResponseResult.success(); |
||||
} |
||||
|
||||
/** |
||||
* 抹掉不应对外返回的字段:密钥摘要一律清空,手机号脱敏。 |
||||
* |
||||
* @param userSecret 待处理的对象。 |
||||
*/ |
||||
private void maskForResponse(SysUserSecret userSecret) { |
||||
userSecret.setSecretHash(null); |
||||
if (StrUtil.isNotBlank(userSecret.getMobile())) { |
||||
userSecret.setMobile(StrUtil.hide(userSecret.getMobile(), 3, 7)); |
||||
} |
||||
} |
||||
} |
||||
@ -1,25 +0,0 @@
@@ -1,25 +0,0 @@
|
||||
package apelet.tenantadmin.upms.dao; |
||||
|
||||
import apelet.common.core.base.dao.BaseDaoMapper; |
||||
import apelet.tenantadmin.upms.model.SysUserSecret; |
||||
import org.apache.ibatis.annotations.Param; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 用户对外密钥数据访问操作接口。 |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public interface SysUserSecretMapper extends BaseDaoMapper<SysUserSecret> { |
||||
|
||||
/** |
||||
* 获取用户对外密钥列表(带账号信息)。 |
||||
* |
||||
* @param sysUserSecretFilter 过滤对象。 |
||||
* @param orderBy 排序字符串。 |
||||
* @return 过滤后的对外密钥列表。 |
||||
*/ |
||||
List<SysUserSecret> getSysUserSecretList(@Param("sysUserSecretFilter") SysUserSecret sysUserSecretFilter, @Param("orderBy") String orderBy); |
||||
} |
||||
@ -1,66 +0,0 @@
@@ -1,66 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
||||
<mapper namespace="apelet.tenantadmin.upms.dao.SysUserSecretMapper"> |
||||
<resultMap id="BaseResultMap" type="apelet.tenantadmin.upms.model.SysUserSecret"> |
||||
<id column="user_secret_id" jdbcType="BIGINT" property="userSecretId"/> |
||||
<result column="key_id" jdbcType="VARCHAR" property="keyId"/> |
||||
<result column="user_id" jdbcType="BIGINT" property="userId"/> |
||||
<result column="app_id" jdbcType="BIGINT" property="appId"/> |
||||
<result column="secret_hash" jdbcType="VARCHAR" property="secretHash"/> |
||||
<result column="status" jdbcType="INTEGER" property="status"/> |
||||
<result column="expire_time" jdbcType="TIMESTAMP" property="expireTime"/> |
||||
<result column="last_used_time" jdbcType="TIMESTAMP" property="lastUsedTime"/> |
||||
<result column="create_user_id" jdbcType="BIGINT" property="createUserId"/> |
||||
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/> |
||||
<result column="update_user_id" jdbcType="BIGINT" property="updateUserId"/> |
||||
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/> |
||||
<result column="deleted_flag" jdbcType="INTEGER" property="deletedFlag"/> |
||||
</resultMap> |
||||
|
||||
<resultMap id="BaseResultMapEx" type="apelet.tenantadmin.upms.model.SysUserSecret" extends="BaseResultMap"> |
||||
<result column="login_name" jdbcType="VARCHAR" property="loginName"/> |
||||
<result column="show_name" jdbcType="VARCHAR" property="showName"/> |
||||
<result column="mobile" jdbcType="VARCHAR" property="mobile"/> |
||||
</resultMap> |
||||
|
||||
<sql id="filterRef"> |
||||
<if test="sysUserSecretFilter != null"> |
||||
<if test="sysUserSecretFilter.userId != null"> |
||||
AND xy_sys_user_secret.user_id = #{sysUserSecretFilter.userId} |
||||
</if> |
||||
<if test="sysUserSecretFilter.appId != null"> |
||||
AND xy_sys_user_secret.app_id = #{sysUserSecretFilter.appId} |
||||
</if> |
||||
<if test="sysUserSecretFilter.status != null"> |
||||
AND xy_sys_user_secret.status = #{sysUserSecretFilter.status} |
||||
</if> |
||||
<if test="sysUserSecretFilter.loginName != null and sysUserSecretFilter.loginName != ''"> |
||||
<bind name="safeLoginName" value="'%' + sysUserSecretFilter.loginName + '%'"/> |
||||
AND IFNULL(xy_sys_user.login_name, '') LIKE #{safeLoginName} |
||||
</if> |
||||
<if test="sysUserSecretFilter.mobile != null and sysUserSecretFilter.mobile != ''"> |
||||
<bind name="safeMobile" value="'%' + sysUserSecretFilter.mobile + '%'"/> |
||||
AND IFNULL(xy_sys_user.mobile, '') LIKE #{safeMobile} |
||||
</if> |
||||
</if> |
||||
AND xy_sys_user_secret.deleted_flag = ${@apelet.common.core.constant.GlobalDeletedFlag@NORMAL} |
||||
</sql> |
||||
|
||||
<select id="getSysUserSecretList" resultMap="BaseResultMapEx" parameterType="apelet.tenantadmin.upms.model.SysUserSecret"> |
||||
SELECT |
||||
xy_sys_user_secret.*, |
||||
xy_sys_user.login_name, |
||||
xy_sys_user.show_name, |
||||
xy_sys_user.mobile |
||||
FROM |
||||
xy_sys_user_secret |
||||
LEFT JOIN |
||||
xy_sys_user ON xy_sys_user_secret.user_id = xy_sys_user.user_id |
||||
<where> |
||||
<include refid="filterRef"/> |
||||
</where> |
||||
<if test="orderBy != null and orderBy != ''"> |
||||
ORDER BY ${orderBy} |
||||
</if> |
||||
</select> |
||||
</mapper> |
||||
@ -1,53 +0,0 @@
@@ -1,53 +0,0 @@
|
||||
package apelet.tenantadmin.upms.service; |
||||
|
||||
import apelet.common.core.object.TokenData; |
||||
import apelet.tenantadmin.upms.model.SysUser; |
||||
|
||||
/** |
||||
* 用户会话上下文构建服务接口。 |
||||
* <p>把"登录成功后需要落到 Redis 的那几份缓存"收敛到一处,供登录链路与 MCP 密钥鉴权链路共用, |
||||
* 避免各自实现导致口径不一致。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public interface UserSessionContextService { |
||||
|
||||
/** |
||||
* 生成会话Id,规则与登录链路保持一致:登录名 + 设备类型 + UUID。 |
||||
* |
||||
* @param loginName 登录名。 |
||||
* @param deviceType 设备类型。 |
||||
* @return 会话Id。 |
||||
*/ |
||||
String generateSessionId(String loginName, int deviceType); |
||||
|
||||
/** |
||||
* 依据账号信息组装 TokenData(含部门/岗位/角色)。 |
||||
* |
||||
* @param user 账号对象。 |
||||
* @param sessionId 会话Id。 |
||||
* @param deviceType 设备类型。 |
||||
* @param appCode 第三方开放应用编码,非开放调用时传null。 |
||||
* @return 组装好的 TokenData。 |
||||
*/ |
||||
TokenData buildTokenData(SysUser user, String sessionId, int deviceType, String appCode); |
||||
|
||||
/** |
||||
* 写入会话上下文缓存。 |
||||
* <p>包含:SESSIONID(会话)、DATA_PERM(数据权限)、WHITELISTPERM(白名单URL)。</p> |
||||
* <p><b>不写 PERM(URL权限集合)</b>:本方法当前服务于 MCP 路径,该路径已从登录态拦截器排除、 |
||||
* 不做"菜单×URL"越权校验;登录链路若复用本方法需另行写入 PERM。</p> |
||||
* |
||||
* @param tokenData 已组装好的 TokenData。 |
||||
* @param user 账号对象。 |
||||
*/ |
||||
void putSessionContext(TokenData tokenData, SysUser user); |
||||
|
||||
/** |
||||
* 清理指定会话的全部上下文缓存。 |
||||
* |
||||
* @param sessionId 会话Id。 |
||||
*/ |
||||
void removeSessionContext(String sessionId); |
||||
} |
||||
@ -0,0 +1,42 @@
@@ -0,0 +1,42 @@
|
||||
package apelet.common.core.mcp.auth.config; |
||||
|
||||
import apelet.common.core.mcp.auth.interceptor.McpAuthInterceptor; |
||||
import apelet.common.core.mcp.auth.spi.McpAuthService; |
||||
import org.springframework.beans.factory.ObjectProvider; |
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
||||
import org.springframework.context.annotation.Configuration; |
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; |
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
||||
|
||||
/** |
||||
* MCP 端点鉴权的自动装配。 |
||||
* <p>MCP 端点本身在 core,鉴权也应随端点一起生效,否则引入了 core 的应用会暴露一个未鉴权端点。 |
||||
* 因此拦截器在这里自动注册,应用无需再写配置;只需要提供 {@link McpAuthService} 实现。</p> |
||||
* <p><b>开关</b>:仅当 {@code apelet.mcp.enabled=true} 时生效。默认关闭,避免引入 core 的应用 |
||||
* (如同步服务、鉴权中心等)无意间暴露 MCP 端点。</p> |
||||
* <p><b>应用侧仍需做一件事</b>:若应用有自己的登录态拦截器注册在 {@code /tenantadmin/**} 上, |
||||
* 必须把 {@code /tenantadmin/mcp} 与 {@code /tenantadmin/mcp/**} 排除,否则未带登录令牌的密钥调用 |
||||
* 会被登录态拦截器抢先拒绝。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Configuration |
||||
@ConditionalOnProperty(name = "apelet.mcp.enabled", havingValue = "true") |
||||
public class McpWebMvcConfig implements WebMvcConfigurer { |
||||
|
||||
private final ObjectProvider<McpAuthService> mcpAuthServiceProvider; |
||||
|
||||
public McpWebMvcConfig(ObjectProvider<McpAuthService> mcpAuthServiceProvider) { |
||||
this.mcpAuthServiceProvider = mcpAuthServiceProvider; |
||||
} |
||||
|
||||
@Override |
||||
public void addInterceptors(InterceptorRegistry registry) { |
||||
// HandlerInterceptor 即使标了 @Component 也不会被 Spring Boot 自动注册,必须在这里显式挂上。
|
||||
// getIfAvailable() 允许应用暂时不实现 SPI:此时拦截器仍会注册,但所有请求一律 401(fail-closed)。
|
||||
registry.addInterceptor(new McpAuthInterceptor(mcpAuthServiceProvider.getIfAvailable())) |
||||
.addPathPatterns(McpAuthInterceptor.MCP_ENDPOINT_PATH) |
||||
.addPathPatterns(McpAuthInterceptor.MCP_ENDPOINT_PATH + "/**"); |
||||
} |
||||
} |
||||
@ -0,0 +1,142 @@
@@ -0,0 +1,142 @@
|
||||
package apelet.common.core.mcp.auth.interceptor; |
||||
|
||||
import apelet.common.core.constant.ApplicationConstant; |
||||
import apelet.common.core.constant.ErrorCodeEnum; |
||||
import apelet.common.core.mcp.auth.spi.McpAuthResult; |
||||
import apelet.common.core.mcp.auth.spi.McpAuthService; |
||||
import apelet.common.core.object.ResponseResult; |
||||
import apelet.common.core.object.TokenData; |
||||
import cn.hutool.core.util.StrUtil; |
||||
import com.alibaba.fastjson.JSON; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.web.context.request.RequestContextHolder; |
||||
import org.springframework.web.context.request.ServletRequestAttributes; |
||||
import org.springframework.web.servlet.HandlerInterceptor; |
||||
|
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
import javax.servlet.http.HttpServletRequestWrapper; |
||||
import java.io.IOException; |
||||
import java.io.PrintWriter; |
||||
|
||||
/** |
||||
* MCP 端点({@code /tenantadmin/mcp})的鉴权拦截器。 |
||||
* <p>支持两种调用方身份,按顺序判定:</p> |
||||
* <ol> |
||||
* <li>{@code Authorization: Bearer <jwt>} —— 登录态,兼容以登录 token 连接 MCP 的现有调用方;</li> |
||||
* <li>人员标识头 + 人员密钥头 —— 人员级凭证,锁定到具体账号(头名称由 {@link McpAuthService} 约定)。</li> |
||||
* </ol> |
||||
* <p>两者都带时以 Bearer 优先,避免调用方主动降级到密钥分支。</p> |
||||
* <p>凭证校验全部委托给 {@link McpAuthService}:JWT 需要应用的签名密钥,密钥需要账号表与应用表, |
||||
* 这些都属于应用侧能力,core 不直接依赖。</p> |
||||
* <p><b>本拦截器由 {@code McpWebMvcConfig} 自动注册</b>,应用只需提供 {@link McpAuthService} 实现。 |
||||
* 若应用未实现该 SPI,所有请求一律 401(fail-closed)。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Slf4j |
||||
public class McpAuthInterceptor implements HandlerInterceptor { |
||||
|
||||
/** |
||||
* MCP 端点路径。该路径同时被 {@code McpStreamableController} 使用,两边必须保持一致。 |
||||
*/ |
||||
public static final String MCP_ENDPOINT_PATH = "/tenantadmin/mcp"; |
||||
|
||||
/** |
||||
* 人员钥匙凭证请求头的默认名称;实际名称由 {@link McpAuthService} 约定,此处仅用于读取。 |
||||
*/ |
||||
public static final String HEADER_MCP_USER = "X-Mcp-User"; |
||||
public static final String HEADER_MCP_SECRET = "X-Mcp-Secret"; |
||||
|
||||
/** |
||||
* 登录态请求头兜底名称(MCP 规范要求使用 Authorization)。 |
||||
*/ |
||||
private static final String DEFAULT_BEARER_HEADER = "Authorization"; |
||||
|
||||
private final McpAuthService mcpAuthService; |
||||
|
||||
public McpAuthInterceptor(McpAuthService mcpAuthService) { |
||||
this.mcpAuthService = mcpAuthService; |
||||
} |
||||
|
||||
@Override |
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { |
||||
if (mcpAuthService == null) { |
||||
log.error("MCP 端点鉴权未配置:应用未提供 McpAuthService 实现。"); |
||||
this.outputUnauthorized(response, "MCP 鉴权未配置,请联系管理员!"); |
||||
return false; |
||||
} |
||||
String bearerHeader = StrUtil.blankToDefault(mcpAuthService.getBearerHeaderName(), DEFAULT_BEARER_HEADER); |
||||
String authorization = request.getHeader(bearerHeader); |
||||
McpAuthResult authResult; |
||||
if (StrUtil.isNotBlank(authorization)) { |
||||
authResult = mcpAuthService.authenticateByJwt(authorization); |
||||
} else { |
||||
String mobile = request.getHeader(HEADER_MCP_USER); |
||||
String credential = request.getHeader(HEADER_MCP_SECRET); |
||||
if (StrUtil.isBlank(mobile) && StrUtil.isBlank(credential)) { |
||||
this.outputUnauthorized(response, "缺少调用凭证,请提供登录令牌或人员密钥!"); |
||||
return false; |
||||
} |
||||
authResult = mcpAuthService.authenticateByUserSecret(mobile, credential); |
||||
} |
||||
if (authResult == null || !authResult.isSuccess() || authResult.getTokenData() == null) { |
||||
String message = authResult == null ? "鉴权失败!" : authResult.getErrorMessage(); |
||||
log.warn("MCP 鉴权失败,keyId={}, 原因={}", authResult == null ? null : authResult.getKeyId(), message); |
||||
this.outputUnauthorized(response, message); |
||||
return false; |
||||
} |
||||
TokenData.addToRequest(authResult.getTokenData()); |
||||
// 在线表单引擎需要 MenuId 头来选取数据权限规则分支;MCP 无菜单上下文,统一按"通用规则"处理。
|
||||
this.wrapRequestWithMenuId(request); |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* 用 HttpServletRequestWrapper 覆盖 MenuId 请求头。 |
||||
* <p>拦截器无法修改已传入的 request 对象,只能包装后替换 RequestContextHolder 中的引用, |
||||
* 使下游通过 ContextUtil.getHttpRequest().getHeader("MenuId") 能取到值。</p> |
||||
* |
||||
* @param request 当前请求。 |
||||
*/ |
||||
private void wrapRequestWithMenuId(HttpServletRequest request) { |
||||
if (StrUtil.isNotBlank(request.getHeader(ApplicationConstant.HTTP_HEADER_MENU_ID))) { |
||||
return; |
||||
} |
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); |
||||
if (attributes == null) { |
||||
return; |
||||
} |
||||
RequestContextHolder.setRequestAttributes( |
||||
new ServletRequestAttributes(new MenuIdHeaderRequestWrapper(request), attributes.getResponse())); |
||||
} |
||||
|
||||
/** |
||||
* 仅覆盖 MenuId 请求头,其余行为全部委托给原请求(含 attribute 读写,TokenData 依赖它)。 |
||||
*/ |
||||
private static class MenuIdHeaderRequestWrapper extends HttpServletRequestWrapper { |
||||
|
||||
MenuIdHeaderRequestWrapper(HttpServletRequest request) { |
||||
super(request); |
||||
} |
||||
|
||||
@Override |
||||
public String getHeader(String name) { |
||||
if (ApplicationConstant.HTTP_HEADER_MENU_ID.equalsIgnoreCase(name)) { |
||||
return ApplicationConstant.DATA_PERM_ALL_MENU_ID; |
||||
} |
||||
return super.getHeader(name); |
||||
} |
||||
} |
||||
|
||||
private void outputUnauthorized(HttpServletResponse response, String message) throws IOException { |
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
||||
response.setHeader("WWW-Authenticate", "Bearer"); |
||||
response.setContentType("application/json; charset=utf-8"); |
||||
PrintWriter out = response.getWriter(); |
||||
out.print(JSON.toJSONString(ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED_LOGIN, message))); |
||||
out.flush(); |
||||
out.close(); |
||||
} |
||||
} |
||||
@ -0,0 +1,33 @@
@@ -0,0 +1,33 @@
|
||||
package apelet.common.core.mcp.auth.session; |
||||
|
||||
import apelet.common.core.object.TokenData; |
||||
|
||||
/** |
||||
* 会话上下文构建 SPI。 |
||||
* <p>登录成功后需要写入 Redis 的那组缓存(会话、数据权限、白名单等)依赖应用的账号/角色/权限体系, |
||||
* core 不能直接实现,故只定义契约。</p> |
||||
* <p>实现方应自带会话复用:同一账号在有效期内重复调用应返回同一份会话,避免每个请求都重建 |
||||
* (一次重建包含若干次查库与多次 Redis 写入)。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public interface UserSessionContextService { |
||||
|
||||
/** |
||||
* 为指定账号构建会话上下文并写入缓存。 |
||||
* |
||||
* @param userId 用户Id。 |
||||
* @param appCode 第三方开放应用编码,非开放调用时传null。 |
||||
* @param deviceType 设备类型。 |
||||
* @return 可直接注入请求上下文的 TokenData。 |
||||
*/ |
||||
TokenData buildAndCacheSession(Long userId, String appCode, int deviceType); |
||||
|
||||
/** |
||||
* 清理指定会话的全部上下文缓存。 |
||||
* |
||||
* @param sessionId 会话Id。 |
||||
*/ |
||||
void removeSessionContext(String sessionId); |
||||
} |
||||
@ -0,0 +1,91 @@
@@ -0,0 +1,91 @@
|
||||
package apelet.common.core.mcp.auth.spi; |
||||
|
||||
/** |
||||
* MCP 鉴权所需的账号信息。 |
||||
* <p>只暴露构建 {@code TokenData} 与做手机号比对所必需的字段,不暴露密码等敏感信息。 |
||||
* {@code isAdmin} 由应用侧按自己的用户类型枚举计算后填入,避免 core 依赖具体应用的枚举。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public class McpAccountInfo { |
||||
|
||||
private Long userId; |
||||
private String loginName; |
||||
private String showName; |
||||
private Long deptId; |
||||
private String mobile; |
||||
private String headImageUrl; |
||||
/** |
||||
* 是否管理员。应用侧按自己的用户类型判定后填入。 |
||||
*/ |
||||
private Boolean isAdmin; |
||||
/** |
||||
* 账号当前是否可用(未锁定/未停用)。应用侧按自己的用户状态判定后填入。 |
||||
*/ |
||||
private Boolean enabled; |
||||
|
||||
public Long getUserId() { |
||||
return userId; |
||||
} |
||||
|
||||
public void setUserId(Long userId) { |
||||
this.userId = userId; |
||||
} |
||||
|
||||
public String getLoginName() { |
||||
return loginName; |
||||
} |
||||
|
||||
public void setLoginName(String loginName) { |
||||
this.loginName = loginName; |
||||
} |
||||
|
||||
public String getShowName() { |
||||
return showName; |
||||
} |
||||
|
||||
public void setShowName(String showName) { |
||||
this.showName = showName; |
||||
} |
||||
|
||||
public Long getDeptId() { |
||||
return deptId; |
||||
} |
||||
|
||||
public void setDeptId(Long deptId) { |
||||
this.deptId = deptId; |
||||
} |
||||
|
||||
public String getMobile() { |
||||
return mobile; |
||||
} |
||||
|
||||
public void setMobile(String mobile) { |
||||
this.mobile = mobile; |
||||
} |
||||
|
||||
public String getHeadImageUrl() { |
||||
return headImageUrl; |
||||
} |
||||
|
||||
public void setHeadImageUrl(String headImageUrl) { |
||||
this.headImageUrl = headImageUrl; |
||||
} |
||||
|
||||
public Boolean getIsAdmin() { |
||||
return isAdmin; |
||||
} |
||||
|
||||
public void setIsAdmin(Boolean isAdmin) { |
||||
this.isAdmin = isAdmin; |
||||
} |
||||
|
||||
public Boolean getEnabled() { |
||||
return enabled; |
||||
} |
||||
|
||||
public void setEnabled(Boolean enabled) { |
||||
this.enabled = enabled; |
||||
} |
||||
} |
||||
@ -0,0 +1,31 @@
@@ -0,0 +1,31 @@
|
||||
package apelet.common.core.mcp.auth.spi; |
||||
|
||||
import java.util.Collection; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* MCP 账号信息查询 SPI。 |
||||
* <p>人员密钥的校验需要读账号的手机号与状态,密钥列表需要展示账号姓名,但账号模型属于应用侧, |
||||
* core 与 common 模块都不能直接依赖,因此由应用实现本接口注入。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public interface McpAccountProvider { |
||||
|
||||
/** |
||||
* 按用户Id查询 MCP 鉴权所需的账号信息。 |
||||
* |
||||
* @param userId 用户Id。 |
||||
* @return 账号信息;不存在时返回null。 |
||||
*/ |
||||
McpAccountInfo getById(Long userId); |
||||
|
||||
/** |
||||
* 按用户Id批量查询账号信息,用于列表展示补全。 |
||||
* |
||||
* @param userIds 用户Id集合。 |
||||
* @return 账号信息列表;入参为空时返回空列表。 |
||||
*/ |
||||
List<McpAccountInfo> listByIds(Collection<Long> userIds); |
||||
} |
||||
@ -0,0 +1,56 @@
@@ -0,0 +1,56 @@
|
||||
package apelet.common.core.mcp.auth.spi; |
||||
|
||||
import apelet.common.core.object.TokenData; |
||||
|
||||
/** |
||||
* MCP 鉴权结果。 |
||||
* <p>成功时携带已注入请求上下文所需的 {@code TokenData};失败时携带可直接返回给调用方的错误信息。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public class McpAuthResult { |
||||
|
||||
private boolean success; |
||||
private TokenData tokenData; |
||||
/** |
||||
* 通过人员密钥鉴权时的 keyId,仅用于日志审计;登录态分支为null。 |
||||
*/ |
||||
private String keyId; |
||||
private String errorMessage; |
||||
|
||||
public static McpAuthResult ok(TokenData tokenData) { |
||||
return ok(tokenData, null); |
||||
} |
||||
|
||||
public static McpAuthResult ok(TokenData tokenData, String keyId) { |
||||
McpAuthResult result = new McpAuthResult(); |
||||
result.success = true; |
||||
result.tokenData = tokenData; |
||||
result.keyId = keyId; |
||||
return result; |
||||
} |
||||
|
||||
public static McpAuthResult fail(String errorMessage) { |
||||
McpAuthResult result = new McpAuthResult(); |
||||
result.success = false; |
||||
result.errorMessage = errorMessage; |
||||
return result; |
||||
} |
||||
|
||||
public boolean isSuccess() { |
||||
return success; |
||||
} |
||||
|
||||
public TokenData getTokenData() { |
||||
return tokenData; |
||||
} |
||||
|
||||
public String getKeyId() { |
||||
return keyId; |
||||
} |
||||
|
||||
public String getErrorMessage() { |
||||
return errorMessage; |
||||
} |
||||
} |
||||
@ -0,0 +1,40 @@
@@ -0,0 +1,40 @@
|
||||
package apelet.common.core.mcp.auth.spi; |
||||
|
||||
/** |
||||
* MCP 端点鉴权 SPI。 |
||||
* <p>MCP 端点在 core({@code McpStreamableController}),但两种凭证的校验都依赖应用侧能力: |
||||
* 登录态 JWT 需要应用的签名密钥与会话存储,人员密钥需要账号表与应用表。 |
||||
* 因此 core 只定义契约,由应用实现。</p> |
||||
* <p><b>实现方必须 fail-closed</b>:任何无法识别的凭证都要返回失败,不能放行。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public interface McpAuthService { |
||||
|
||||
/** |
||||
* 登录态 JWT 所在的请求头名称。 |
||||
* <p>MCP 规范要求使用 {@code Authorization};由应用返回自己的配置值,避免 core 硬编码。 |
||||
* 应用未配置时返回 null,拦截器按 {@code Authorization} 兜底。</p> |
||||
* |
||||
* @return 请求头名称。 |
||||
*/ |
||||
String getBearerHeaderName(); |
||||
|
||||
/** |
||||
* 校验登录态 JWT 并取回会话中的身份。 |
||||
* |
||||
* @param token 请求头中的完整取值(含 Bearer 前缀)。 |
||||
* @return 鉴权结果。 |
||||
*/ |
||||
McpAuthResult authenticateByJwt(String token); |
||||
|
||||
/** |
||||
* 校验"手机号 + 人员密钥"。 |
||||
* |
||||
* @param mobile 调用方声明的手机号。 |
||||
* @param credential 完整凭证,格式为 "keyId.secret"。 |
||||
* @return 鉴权结果。 |
||||
*/ |
||||
McpAuthResult authenticateByUserSecret(String mobile, String credential); |
||||
} |
||||
@ -0,0 +1,41 @@
@@ -0,0 +1,41 @@
|
||||
package apelet.common.openapi.constant; |
||||
|
||||
/** |
||||
* 人员密钥的凭证规格常量。 |
||||
* <p><b>本类中的参数是安全参数,不是运维参数,不要改成配置项。</b> |
||||
* 理由:secret 只存 SHA-256 摘要(不是 BCrypt 这类慢哈希,无法用计算代价补偿短口令), |
||||
* 长度就是唯一的强度来源;keyId 的长度还受数据库列宽约束。改这里等于改安全强度, |
||||
* 必须走代码评审而不是改配置。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public final class SysUserSecretSpec { |
||||
|
||||
/** |
||||
* keyId 与 secret 的字符集:大小写字母 + 数字,共 62 个字符。 |
||||
* <p>不用特殊符号是为了便于复制粘贴、避免转义与手输歧义。 |
||||
* <b>调小字符集等于按比例削减熵</b>,例如去掉大写字母会让 32 位的熵从约 190 bit 降到约 165 bit。</p> |
||||
*/ |
||||
public static final String RANDOM_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
||||
|
||||
/** |
||||
* keyId 长度。 |
||||
* <p><b>受存储约束</b>:`xy_sys_user_secret.key_id` 为 `varchar(32)`,调大必须同步修改建表脚本, |
||||
* 否则插入会被截断或直接报错。</p> |
||||
*/ |
||||
public static final int KEY_ID_LENGTH = 32; |
||||
|
||||
/** |
||||
* secret 长度。 |
||||
* <p><b>这是安全强度本身</b>。32 位 × 字符集 62 ⇒ 约 190 bit 熵,远超需要。 |
||||
* 若降到 8 位则只有约 48 bit,在摘要泄漏的前提下可被离线爆破。</p> |
||||
*/ |
||||
public static final int SECRET_LENGTH = 32; |
||||
|
||||
/** |
||||
* 私有构造函数,明确标识该常量类的作用。 |
||||
*/ |
||||
private SysUserSecretSpec() { |
||||
} |
||||
} |
||||
@ -1,4 +1,4 @@
@@ -1,4 +1,4 @@
|
||||
package apelet.tenantadmin.upms.model.constant; |
||||
package apelet.common.openapi.constant; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
@ -0,0 +1,245 @@
@@ -0,0 +1,245 @@
|
||||
package apelet.common.openapi.controller; |
||||
|
||||
import apelet.common.core.annotation.MyRequestBody; |
||||
import apelet.common.core.constant.ErrorCodeEnum; |
||||
import apelet.common.core.mcp.auth.spi.McpAccountInfo; |
||||
import apelet.common.core.mcp.auth.spi.McpAccountProvider; |
||||
import apelet.common.core.object.MyPageData; |
||||
import apelet.common.core.object.MyPageParam; |
||||
import apelet.common.core.object.ResponseResult; |
||||
import apelet.common.core.object.TokenData; |
||||
import apelet.common.core.util.MyCommonUtil; |
||||
import apelet.common.core.util.MyPageUtil; |
||||
import apelet.common.log.annotation.OperationLog; |
||||
import apelet.common.log.model.constant.SysOperationLogType; |
||||
import apelet.common.openapi.constant.SysUserSecretStatus; |
||||
import apelet.common.openapi.model.SysUserSecret; |
||||
import apelet.common.openapi.service.SysUserSecretService; |
||||
import apelet.common.openapi.vo.SysUserSecretIssueVo; |
||||
import cn.hutool.core.date.DateUtil; |
||||
import cn.hutool.core.util.StrUtil; |
||||
import com.github.pagehelper.Page; |
||||
import com.github.pagehelper.page.PageMethod; |
||||
import io.swagger.v3.oas.annotations.tags.Tag; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.web.bind.annotation.PostMapping; |
||||
import org.springframework.web.bind.annotation.RequestMapping; |
||||
import org.springframework.web.bind.annotation.RestController; |
||||
|
||||
import java.util.*; |
||||
import java.util.function.Function; |
||||
import java.util.stream.Collectors; |
||||
|
||||
/** |
||||
* 用户对外密钥管理接口。 |
||||
* <p><b>签发是自助的</b>:密钥只能签发给当前登录人自己(userId 取自登录态),不需要管理员代发, |
||||
* 明文也不经过第三人。绑定的 OpenAPI 应用取自配置项 {@code apelet.mcp.app-code}。</p> |
||||
* <p><b>归属校验</b>:非管理员只能看到、操作自己的密钥。这层校验是必需的——自助签发意味着这些接口 |
||||
* 会对普通登录用户开放,而 {@code resetSecret} 会返回明文新密钥,若不校验归属, |
||||
* 任何人都能通过传入他人的记录Id拿到他人的凭证。</p> |
||||
* <p>响应中永远不返回 secretHash;明文 secret 只在签发/轮换的响应里出现一次, |
||||
* 且对应操作日志显式关闭了响应体记录(saveResponse=false),避免明文密钥落到日志。</p> |
||||
* <p>账号姓名/手机号属于应用侧数据,通过 {@link McpAccountProvider} SPI 补全, |
||||
* 本模块不依赖具体应用的账号模型。</p> |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
@Tag(name = "对外密钥管理") |
||||
@Slf4j |
||||
@RestController |
||||
@RequestMapping("${common-openapi.urlPrefix:/openapi}/userSecret") |
||||
public class SysUserSecretController { |
||||
|
||||
@Autowired |
||||
private SysUserSecretService sysUserSecretService; |
||||
@Autowired(required = false) |
||||
private McpAccountProvider mcpAccountProvider; |
||||
|
||||
/** |
||||
* 对外密钥分页列表。非管理员只返回自己的密钥。 |
||||
* |
||||
* @param sysUserSecretFilter 过滤条件(userId/appId/status)。 |
||||
* @param pageParam 分页参数。 |
||||
* @return 应答结果对象,包含分页后的密钥列表。 |
||||
*/ |
||||
@PostMapping("/list") |
||||
public ResponseResult<MyPageData<SysUserSecret>> list( |
||||
@MyRequestBody SysUserSecret sysUserSecretFilter, |
||||
@MyRequestBody MyPageParam pageParam) { |
||||
TokenData tokenData = TokenData.takeFromRequest(); |
||||
if (tokenData == null || tokenData.getUserId() == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED_LOGIN); |
||||
} |
||||
SysUserSecret filter = sysUserSecretFilter == null ? new SysUserSecret() : sysUserSecretFilter; |
||||
if (!Boolean.TRUE.equals(tokenData.getIsAdmin())) { |
||||
// 非管理员只能看自己的,忽略其传入的 userId 条件。
|
||||
filter.setUserId(tokenData.getUserId()); |
||||
} |
||||
if (pageParam != null) { |
||||
PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); |
||||
} |
||||
List<SysUserSecret> secretList = sysUserSecretService.getSysUserSecretList(filter); |
||||
long totalCount = 0L; |
||||
if (secretList instanceof Page) { |
||||
totalCount = ((Page<SysUserSecret>) secretList).getTotal(); |
||||
} |
||||
this.fillAccountInfo(secretList); |
||||
secretList.forEach(this::maskForResponse); |
||||
return ResponseResult.success(MyPageUtil.makeResponseData(secretList, totalCount)); |
||||
} |
||||
|
||||
/** |
||||
* 查看指定密钥的详情。非管理员只能查看自己的。不返回 secretHash。 |
||||
* |
||||
* @param userSecretId 密钥记录主键Id。 |
||||
* @return 应答结果对象,包含密钥详情。 |
||||
*/ |
||||
@PostMapping("/view") |
||||
public ResponseResult<SysUserSecret> view(@MyRequestBody Long userSecretId) { |
||||
if (MyCommonUtil.existBlankArgument(userSecretId)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
SysUserSecret userSecret = sysUserSecretService.getById(userSecretId); |
||||
if (userSecret == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
if (!this.isSelfOrAdmin(userSecret)) { |
||||
return ResponseResult.error(ErrorCodeEnum.NO_OPERATION_PERMISSION); |
||||
} |
||||
this.fillAccountInfo(Collections.singletonList(userSecret)); |
||||
this.maskForResponse(userSecret); |
||||
return ResponseResult.success(userSecret); |
||||
} |
||||
|
||||
/** |
||||
* 为当前登录人签发一把对外密钥。明文只在本响应中出现一次,之后无法再查。 |
||||
* <p><b>不能标注 {@code @NoAuthInterface}</b>:本方法依赖 {@code TokenData.takeFromRequest()} 取当前用户, |
||||
* 而该方法在没有请求属性时会回退去解析请求头 {@code tokenData} 的 JSON,客户端可以伪造整个身份。 |
||||
* 普通用户要能调本接口,正确做法是把本 URL 加入权限白名单(见建表脚本), |
||||
* 白名单只跳过 URL 权限校验、不跳过登录校验。</p> |
||||
* |
||||
* @param expireTime 过期时间字符串,留空表示永不过期。 |
||||
* @return 应答结果对象,包含 keyId、明文 secret 与完整凭证。 |
||||
*/ |
||||
@OperationLog(type = SysOperationLogType.ADD, saveResponse = false) |
||||
@PostMapping("/issue") |
||||
public ResponseResult<SysUserSecretIssueVo> issue(@MyRequestBody String expireTime) { |
||||
TokenData tokenData = TokenData.takeFromRequest(); |
||||
if (tokenData == null || tokenData.getUserId() == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED_LOGIN); |
||||
} |
||||
Date expireDate = null; |
||||
if (StrUtil.isNotBlank(expireTime)) { |
||||
expireDate = DateUtil.parse(expireTime); |
||||
} |
||||
return ResponseResult.success(sysUserSecretService.issue(tokenData.getUserId(), expireDate)); |
||||
} |
||||
|
||||
/** |
||||
* 轮换指定密钥的口令:keyId 不变,旧 secret 立即失效。明文只在本响应中出现一次。 |
||||
* <p>非管理员只能轮换自己的密钥——该接口会返回明文,归属校验不可省略。</p> |
||||
* |
||||
* @param userSecretId 密钥记录主键Id。 |
||||
* @return 应答结果对象,包含新的明文 secret 与完整凭证。 |
||||
*/ |
||||
@OperationLog(type = SysOperationLogType.UPDATE, saveResponse = false) |
||||
@PostMapping("/resetSecret") |
||||
public ResponseResult<SysUserSecretIssueVo> resetSecret(@MyRequestBody Long userSecretId) { |
||||
if (MyCommonUtil.existBlankArgument(userSecretId)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
SysUserSecret userSecret = sysUserSecretService.getById(userSecretId); |
||||
if (userSecret == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
if (!this.isSelfOrAdmin(userSecret)) { |
||||
return ResponseResult.error(ErrorCodeEnum.NO_OPERATION_PERMISSION); |
||||
} |
||||
return ResponseResult.success(sysUserSecretService.resetSecret(userSecretId)); |
||||
} |
||||
|
||||
/** |
||||
* 启用/停用指定密钥。停用后该密钥的调用一律拒绝。非管理员只能操作自己的密钥。 |
||||
* |
||||
* @param userSecretId 密钥记录主键Id。 |
||||
* @param status 目标状态(1: 启用 0: 停用)。 |
||||
* @return 应答结果对象。 |
||||
*/ |
||||
@OperationLog(type = SysOperationLogType.UPDATE, saveResponse = false) |
||||
@PostMapping("/updateStatus") |
||||
public ResponseResult<Void> updateStatus(@MyRequestBody Long userSecretId, @MyRequestBody Integer status) { |
||||
if (MyCommonUtil.existBlankArgument(userSecretId, status)) { |
||||
return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST); |
||||
} |
||||
if (!SysUserSecretStatus.isValid(status)) { |
||||
return ResponseResult.error(ErrorCodeEnum.INVALID_STATUS_ARGUMENT); |
||||
} |
||||
SysUserSecret userSecret = sysUserSecretService.getById(userSecretId); |
||||
if (userSecret == null) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
if (!this.isSelfOrAdmin(userSecret)) { |
||||
return ResponseResult.error(ErrorCodeEnum.NO_OPERATION_PERMISSION); |
||||
} |
||||
if (!sysUserSecretService.updateStatus(userSecretId, status)) { |
||||
return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "对外密钥不存在,请刷新后重试!"); |
||||
} |
||||
return ResponseResult.success(); |
||||
} |
||||
|
||||
/** |
||||
* 补全账号展示字段。密钥表本身不含账号信息,通过 SPI 批量补齐。 |
||||
* |
||||
* @param secretList 密钥列表。 |
||||
*/ |
||||
private void fillAccountInfo(List<SysUserSecret> secretList) { |
||||
if (secretList == null || secretList.isEmpty() || mcpAccountProvider == null) { |
||||
return; |
||||
} |
||||
Set<Long> userIdSet = secretList.stream().map(SysUserSecret::getUserId).filter(Objects::nonNull).collect(Collectors.toSet()); |
||||
if (userIdSet.isEmpty()) { |
||||
return; |
||||
} |
||||
Map<Long, McpAccountInfo> accountMap = mcpAccountProvider.listByIds(userIdSet).stream() |
||||
.collect(Collectors.toMap(McpAccountInfo::getUserId, Function.identity(), (a, b) -> a)); |
||||
for (SysUserSecret userSecret : secretList) { |
||||
McpAccountInfo account = accountMap.get(userSecret.getUserId()); |
||||
if (account != null) { |
||||
userSecret.setLoginName(account.getLoginName()); |
||||
userSecret.setShowName(account.getShowName()); |
||||
userSecret.setMobile(account.getMobile()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 判断当前登录人是否有权操作该密钥:管理员放行,否则要求是该密钥的绑定账号。 |
||||
* |
||||
* @param userSecret 目标密钥记录。 |
||||
* @return 有权操作返回true,否则false。 |
||||
*/ |
||||
private boolean isSelfOrAdmin(SysUserSecret userSecret) { |
||||
TokenData tokenData = TokenData.takeFromRequest(); |
||||
if (tokenData == null || tokenData.getUserId() == null) { |
||||
return false; |
||||
} |
||||
if (Boolean.TRUE.equals(tokenData.getIsAdmin())) { |
||||
return true; |
||||
} |
||||
return Objects.equals(tokenData.getUserId(), userSecret.getUserId()); |
||||
} |
||||
|
||||
/** |
||||
* 抹掉不应对外返回的字段:密钥摘要一律清空,手机号脱敏。 |
||||
* |
||||
* @param userSecret 待处理的对象。 |
||||
*/ |
||||
private void maskForResponse(SysUserSecret userSecret) { |
||||
userSecret.setSecretHash(null); |
||||
if (StrUtil.isNotBlank(userSecret.getMobile())) { |
||||
userSecret.setMobile(StrUtil.hide(userSecret.getMobile(), 3, 7)); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,13 @@
@@ -0,0 +1,13 @@
|
||||
package apelet.common.openapi.dao; |
||||
|
||||
import apelet.common.core.base.dao.BaseDaoMapper; |
||||
import apelet.common.openapi.model.SysUserSecret; |
||||
|
||||
/** |
||||
* 用户对外密钥数据访问操作接口。 |
||||
* |
||||
* @author chenchuchuan |
||||
* @date 2026-10-14 |
||||
*/ |
||||
public interface SysUserSecretMapper extends BaseDaoMapper<SysUserSecret> { |
||||
} |
||||
@ -1,4 +1,4 @@
@@ -1,4 +1,4 @@
|
||||
package apelet.tenantadmin.upms.model; |
||||
package apelet.common.openapi.model; |
||||
|
||||
import apelet.common.core.base.model.BaseModel; |
||||
import com.baomidou.mybatisplus.annotation.TableField; |
||||
Loading…
Reference in new issue