From 58e17190eafae2558af84f9ef4de8e6a3a80ccbc Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 13 Sep 2026 15:41:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(backend):=20JWT=20=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E7=BB=AD=E6=9C=9F=EF=BC=88=E5=89=A9=E4=BD=99=E6=9C=89=E6=95=88?= =?UTF-8?q?=E6=9C=9F=E4=B8=8D=E8=B6=B3=E9=98=88=E5=80=BC=E6=97=B6=E5=93=8D?= =?UTF-8?q?=E5=BA=94=E5=A4=B4=E4=B8=8B=E5=8F=91=E6=96=B0=20token=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config.jwt 新增 renewThreshold(默认 1800s,0=关闭)与 renewHeader(默认 X-Refresh-Token) - jwt_auth 中间件校验通过后计算 exp 剩余秒数,低于阈值则用同一套登录参数签发新 token 写入响应头 响应头在 next() 之前设置,业务接口返回 4xx/5xx 时也会带上;同时下发 Access-Control-Expose-Headers 供跨域读取 --- backend/app/middleware/jwt_auth.js | 37 +++++++++++++++++++++++++++++- backend/config/config.default.js | 4 ++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/backend/app/middleware/jwt_auth.js b/backend/app/middleware/jwt_auth.js index 1313488..bd9712e 100644 --- a/backend/app/middleware/jwt_auth.js +++ b/backend/app/middleware/jwt_auth.js @@ -5,7 +5,9 @@ const TOKEN_PREFIX = 'Bearer '; /** * JWT 鉴权中间件 * 校验请求头 Authorization: Bearer ,解析出 user_id 后加载用户信息(Redis 缓存优先,避免频繁查库), - * 并把用户信息与其可用主体ID列表挂载到 ctx,供控制器与后续中间件复用 + * 并把用户信息与其可用主体ID列表挂载到 ctx,供控制器与后续中间件复用; + * 同时支持自动续期:token 剩余有效期不足 config.jwt.renewThreshold 秒时, + * 在本次响应头 config.jwt.renewHeader(默认 X-Refresh-Token)下发新 token,由前端更新本地存储。 * @return {Function} koa 中间件 */ module.exports = () => { @@ -57,6 +59,39 @@ module.exports = () => { ctx.userPrincipalIds = principalIds || []; ctx.state.principalIds = principalIds || []; + // 自动续期:token 剩余有效期不足阈值时,本次响应头下发新 token(前端据此更新本地存储) + // 注:响应头在 next() 之前设置,即使后续接口返回 4xx/5xx 也会带上,便于前端同步 + setRefreshTokenHeader(ctx, app, decoded, userId); + await next(); }; }; + +/** + * 按「剩余有效期」决定是否下发新 token + * - 阈值来自 config.jwt.renewThreshold(秒),<= 0 或 0 时关闭续期 + * - 新 token 与登录签发参数完全一致(载荷仅 user_id,有效期取 config.jwt.expiresIn) + * - 同时设置 Access-Control-Expose-Headers,保证跨域场景前端也能读到该响应头 + * @param {Object} ctx egg context + * @param {Object} app egg application + * @param {Object} decoded 当前 token 载荷(含 exp) + * @param {Number} userId 用户ID + * @return {void} + */ +function setRefreshTokenHeader(ctx, app, decoded, userId) { + const jwtConfig = app.config.jwt || {}; + const threshold = Number(jwtConfig.renewThreshold || 0); + const headerName = jwtConfig.renewHeader || 'X-Refresh-Token'; + if (!(threshold > 0)) return; + + const exp = Number(decoded.exp) || 0; + if (!exp) return; + const remainSeconds = exp - Math.floor(Date.now() / 1000); + if (remainSeconds > threshold) return; + + const expiresIn = jwtConfig.expiresIn || '2h'; + const token = app.jwt.sign({ user_id: userId }, jwtConfig.secret, { expiresIn }); + ctx.set(headerName, token); + ctx.set('Access-Control-Expose-Headers', headerName); + ctx.logger.info(`[jwt] 用户 ${userId} 的 token 剩余 ${remainSeconds}s(<= ${threshold}s),已下发新 token`); +} diff --git a/backend/config/config.default.js b/backend/config/config.default.js index f4fb388..7b408b9 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -121,9 +121,13 @@ module.exports = appInfo => { }; // JWT 配置:secret 必须通过环境变量 JWT_SECRET 覆盖,切勿使用默认值上生产 + // 自动续期:token 剩余有效期小于 renewThreshold 秒时,本次响应头(renewHeader)下发新 token, + // 前端读取该响应头并更新本地存储,活跃用户可无感续期;renewThreshold 设 0 可关闭续期 config.jwt = { secret: process.env.JWT_SECRET || 'oms-dev-jwt-secret-change-me', expiresIn: process.env.JWT_EXPIRES_IN || '2h', + renewThreshold: Number(process.env.JWT_RENEW_THRESHOLD || 1800), + renewHeader: process.env.JWT_RENEW_HEADER || 'X-Refresh-Token', }; // swagger 文档:UI 访问 /swagger-ui.html,JSON 访问 /swagger-doc