权限验证JWT

2021-12-13 20:57:16 浏览数 (1)

1. 结构

  • Header
代码语言:javascript复制
{
    "alg": "HS256",
    "type": "JWT"
}
  • Payload
代码语言:javascript复制
{
    "sub": "123456",
    "name": "John",
    "admin": true
}
  • Signature

2. 服务端token

代码语言:javascript复制
// 生成token
const jwt = require('jsonwebtoken')
const token = jwt.sign({
    data: res
}, 'shortVideo', { expiresIn: 30 })


// 验证token
const token = ctx.request.headers.authorization.split(' ')[1]
const payload = jwt.verify(token, 'shortVideo')
ctx.body = payload

3. 客户端token

代码语言:javascript复制
const service = axios.create({
    baseURL: config.baseApi,
    timeout: 8000
})

service.interceptors.request.use((req) => {
    const headers = req.headers;
    const { token } = storage.getItem('userInfo');
    if(!headers.Authorization) headers.Authorization = 'Bear '   token;
    return req;
})

0 人点赞