Egg Jwt 前端登录鉴权实现,token超过时间后登录失效

框架安装 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,
    });
    
    
  }
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值