oms/backend/app/middleware/jwt_auth.js
liufumingren 58e17190ea feat(backend): JWT 自动续期(剩余有效期不足阈值时响应头下发新 token)
- config.jwt 新增 renewThreshold(默认 1800s,0=关闭)与 renewHeader(默认 X-Refresh-Token)

- jwt_auth 中间件校验通过后计算 exp 剩余秒数,低于阈值则用同一套登录参数签发新 token 写入响应头

  响应头在 next() 之前设置,业务接口返回 4xx/5xx 时也会带上;同时下发 Access-Control-Expose-Headers 供跨域读取
2026-09-13 15:41:27 +08:00

98 lines
3.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const TOKEN_PREFIX = 'Bearer ';
/**
* JWT 鉴权中间件
* 校验请求头 Authorization: Bearer <token>,解析出 user_id 后加载用户信息(Redis 缓存优先,避免频繁查库),
* 并把用户信息与其可用主体ID列表挂载到 ctx,供控制器与后续中间件复用;
* 同时支持自动续期:token 剩余有效期不足 config.jwt.renewThreshold 秒时,
* 在本次响应头 config.jwt.renewHeader(默认 X-Refresh-Token)下发新 token,由前端更新本地存储。
* @return {Function} koa 中间件
*/
module.exports = () => {
return async (ctx, next) => {
const app = ctx.app;
const header = ctx.get('authorization') || '';
const token = header.startsWith(TOKEN_PREFIX) ? header.slice(TOKEN_PREFIX.length) : header;
if (!token) {
ctx.status = 401;
ctx.body = { code: 401, message: '缺少登录凭证,请先登录' };
return;
}
// 仅校验 token 本身,不要把控制器(await next)抛出的业务异常也吞成 401
let decoded;
try {
// token 载荷仅包含 user_id,不含任何敏感信息
decoded = app.jwt.verify(token, app.config.jwt.secret);
} catch (err) {
ctx.status = 401;
ctx.body = { code: 401, message: '登录凭证无效或已过期' };
return;
}
const userId = decoded.user_id;
// 用户信息与可用主体ID均走缓存,命中时不再查库
const [ user, principalIds ] = await Promise.all([
ctx.service.cache.getUser(userId),
ctx.service.cache.getUserPrincipalIds(userId),
]);
if (!user) {
ctx.status = 401;
ctx.body = { code: 401, message: '用户不存在或已被删除' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '账号已禁用' };
return;
}
ctx.userId = userId;
ctx.state.userId = userId;
ctx.user = user;
ctx.state.user = user;
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`);
}