1. 结构
代码语言:javascript
复制{
"alg": "HS256",
"type": "JWT"
}
代码语言:javascript
复制{
"sub": "123456",
"name": "John",
"admin": true
}
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;
})