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