JWT实现token身份验证
npm i jsonwebtoken --save
const jsonwebtoken = require("jsonwebtoken")
const secret = "miyao"
const JWT = {
// 生成token expires过期时间
generate(value, expires) {
return jsonwebtoken.sign(value, secret, { expiresIn:expires })
},
// 验证token
verify(token) {
try {
return jsonwebtoken.verify(token, secret)
} catch (e) {
return false
}
}
}
//导出
module.exports = JWT
在要使用的地方通过require引用.js文件
新建一个axios.config.js文件
import axios from 'axios'
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// 每次发请求,从localStorage中获取token
const token = localStorage.getItem("token")
config.headers.Authorization = `Bearer ${token}`
return config;
}, function (error) {
// // Do something with request error
const { status } = error.response
// 如果响应的状态码为401未经授权
if (status === 401) {
localStorage.removeItem("token")
window.location.href = "#/login"
}
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
// console.log(response.headers,)
// 解构
const { authorization } = response.headers
authorization && localStorage.setItem("token", authorization)
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
tip:生成 token 时加了’Bearer ',验证时要把’Bearer '去掉, req.headers.authorization.split(" ")[1],不然会出现JsonWebTokenError: invalid token的错误,验证失败。
Express.js中间件
// Express.js中间件
app.use((req, res, next) => {
// // 判断是否是login接口 如果是,则直接调用next()函数,跳过后续的中间件和路由处理。
if (req.url === "/adminapi/user/login") {
next()
return;
}
const token = req.headers.authorization.split(" ")[1];
// 如果授权通过 (token有效),next()
if (token) {
// // 校验token
var paylode = JWT.verify(token)
// console.log(paylode, "paylode--")
if (paylode) {
// const newToken = JWT.generate(paylode, "10s")
const newToken = JWT.generate({
_id: paylode._id,
username: paylode.username
}, "1d")
res.header("authorization", newToken)
next()
} else {
// 如果,token过期,返回 401错误
res.status(401).send({ errCode: "-1", errorInfo: "token过期" })
}
}
})