实战解析token验证有效期用法
1.引入node 的jsonwebtoken 模块
npm install jsonwebtoken --save
2.引入模块在登陆接口处使用
注入模块 :var jwt = require('jsonwebtoken')
router.post('/login', async (ctx, next) => { if (!ctx.request.body.phone) { ctx.body = { err: '无效参数phone' } } else if (!ctx.request.body.password) { ctx.body = { err: '无效参数password' } } else { let data = null //生成token const token = jwt.sign( { name: ctx.request.body //需要放到token的参数 }, 'suzhen', //随便一点内容,加密的密文,私钥对应着公钥 { expiresIn: 60 * 60 //60分钟到期时间 } ) data = await DB_QUERY.getOne({ find: { phone: ctx.request.body.phone, password: ctx.request.body.password } }) if (data) ctx.body = { data: { user_id: data._id, token: token }, message: '登陆成功' } else ctx.body = { message: '登陆失败' } } })
3.根据需要的接口处接受并判断token的有效期时间(这里放到的了请求头header里面的x_access_token)
在注册路由的地方用app.use()方法
app.use(async (ctx, next) => { let { url = '' } = ctx if (url.indexOf('/users/login') == -1) { //除去登陆,注册,找回密码等接口其他的都需要验证 //需要校验登录态 if (!ctx.request.header.x_access_token) { return (ctx.body = { err: '无效token' }) } else { try { let token = await jwt.verify( ctx.request.header.x_access_token, 'suzhen' ) if (token.name) await next() else return (ctx.body = { err: '无效token' }) } catch (error) { console.log(error) return (ctx.body = { err: '无效token' }) } } } else { await next() } })
参看链接:jsonwebtoken中文文档