框架安装 egg-jwt
npm i egg-jwt
config配置
pluginjs
jwt : {
enable: true,
package: 'egg-jwt',
},
config.default.js
// 配置tokenHandler中间件
config.jwt = {
secret: 'www.baidu.com',//自定义配置
sign: {
// expiresIn: 60 //测试60s过期
expiresIn: '1d' //1天后过期
}
}
中间件
middleware 文件夹下新建token_handler.js
'use strict'
module.exports = (options, app) => {
return async function tokenHandler(ctx, next) {
let token = ctx.header.authorization; // 获取header里的authorization
if (token) {
let userinfo = null;
try {
token= token.replace('Bearer ', '')
userinfo = ctx.app.jwt.verify(token, options.secret);
if (!userinfo) {
ctx.body = {
data: {
message: '登录过期',
code: 305,
data: null
}
};
return {
message: '登录过期',
code: 305,
data: null
}
}else {
await next();
}
} catch (error) {
console.log(error, '222222====2')
ctx.body = {
data: {
message: '登录过期',
code: 305,
data: null
}
};
return {
message: '登录过期',
code: 305,
data: null
}
}
} else {
ctx.body = {
data: {
message: '你还未登录,请登录',
code: 401,
data: null
}
}
return {
message: '你还未登录,请登录',
code: 401,
data: null
}
}
}
}
接口路由配置需要jwt的接口
router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller, middleware } = app;
const _jwt = middleware.tokenHandler(app.config.jwt); //传入加密字符串
router.post('/users/findByUsername', _jwt, controller.user.findByUsername)
};
前端React项目接口拦截
instance.interceptors.response.use(
(res) => {
NProgress.done();
if(res.data?.data?.code == 200) {
return Promise.resolve(res.data);
}else if(res.data?.data?.code == 305){
setTimeout(()=>{
localStorage.removeItem("token");
store.dispatch(loginOutAction());
window.location.reload()
}, 2000)
return Promise.reject({
code: res.data.data.code,
message: "登录已失效,即将跳转到登录页面!"
});
}else {
return Promise.reject({
code: res.data.data.code,
message: res.data.data.message
});
}
},
(err) => {
NProgress.done();
return Promise.reject({
code: err.response.status,
message: err.response.data.error,
});
}
);