jwt技术点实现的功能如下
1、server端会在前端访问部分接口时做权限认证,server端会声明不需要jwt权限验证的接口,比如login登录接口,对于需要jwt权限验证的接口,如果前端无权限,则server端会返给前端401状态码
2、用户登录成功后,server端就会返回给前端一个加密了的有保质期的字符串,字符串中存储着用户登录的信息,这个字符串就是token,前端拥有未过期的token,就表明前端有访问有权限认证的接口的权限
3、接下来用户再发送网络请求调用server端接口时,就会携带token,用来表明自己的身份
koa-jwt的验证方式
请求头中设置 authorization为Bearer + token,Bearer后有空格
koa-jwt的默认验证方式:
{'authorization': "Bearer " + token}
koa-jwt 搭配 jsonwebtoken 的使用
1. 安装依赖
npm install jsonwebtoken koa-jwt --save
2. 密钥设置
conf/db 文件中
let SECRET = 'blog-nodejs' // token 密钥module.exports = {
SECRET
}
3. 中间件 请求验证token
app.js 文件中
// 导入
const koajwt = require('koa-jwt')
const { SECRET } = require('./conf/db')
// 中间件对token进行验证
app.use(async (ctx, next) => {
return next().catch((err) => {
if (err.status === 401) {
ctx.body = new UnauthorizedModel()
} else {
throw err
}
})
})
4. 不需要验证的接口
app.js 文件中
app.use(koajwt({ secret: SECRET }).unless({
path: [
/^\/api\/login/, // 登陆接口
/^\/api\/register/ // 注册
]
}))
5. 登陆签发token
登陆接口中
// 导入
const { SECRET } = require('../conf/db')
const jsonwebtoken = require('jsonwebtoken')
const res = await login(username, password)
// 登陆成功
if (res.username) {
// 存储用户信息
let info = {
id: res.id,
name: res.username,
realname: res.realname,
}
let data = {
Bearer: 'Bearer ',
// 签发 token,1天
token: jsonwebtoken.sign(
info,
SECRET,
{ expiresIn: '1d' }
)
}
ctx.body = new SuccessModel(data, '登陆成功')
} else {
ctx.body = new ErrorModel('用户名或密码错误')
}
6. 解密token, 获取个人信息
1\. 封装解密函数 payload.js 文件中
const { SECRET } = require('../conf/db')
const jsonwebtoken = require('jsonwebtoken')
const util = require('util')
// 将jwt.verify函数promise化
const verify = util.promisify(jsonwebtoken.verify)
module.exports = async function getPayload (ctx) {
const token = ctx.header.authorization
const payload = await verify(token.split(' ')[1], SECRET)
return payload
}
2\. 获取个人信息接口中
// 导入
const getPayload = require('../utils/payload')
// 获取
const payload = await getPayload(ctx)
console.log(payload)
前端:axios请求
axios.defaults.baseURL = 'http://localhost:8000'
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpYXQiOjE2MDA3MDAxOTYsImV4cCI6MTYwMDcwMzc5Nn0.6QDQto-bwYH27n_JgEzZv4BhVSvoKl_xi3xgQ-ZQdAs'
return config
})
axios.get('/api/blog/list').then((res) => {
console.log(res.data)
})