實戰解析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中文文檔
