'use strict'; const TOKEN_PREFIX = 'Bearer '; /** * JWT 鉴权中间件 * 校验请求头 Authorization: Bearer ,解析后仅取 user_id 挂载到 ctx.userId * @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; } try { // token 载荷仅包含 user_id,不含任何敏感信息 const decoded = app.jwt.verify(token, app.config.jwt.secret); ctx.userId = decoded.user_id; ctx.state.userId = decoded.user_id; await next(); } catch (err) { ctx.status = 401; ctx.body = { code: 401, message: '登录凭证无效或已过期' }; } }; };