egg-jwt 的使用与踩坑

1,162 阅读1分钟

基础配置

  1. 资源下载
    $ npm install egg-jwt --save
    
  2. 插件配置
    // config/plugin.js 
    module.exports = { 
        jwt: { 
            enable: true, 
            package: "egg-jwt" 
        }
        // ...
    };
    
  3. 设置加密字符
    // config/config.default.js 
    config.jwt = { 
        secret: "123456" //自定义 token 的加密条件字符串 
    };
    

如何使用

  1. JWT 注册
    const token = app.jwt.sign(
    { 
        username: data,  // 默认字段
        // key: value,       // 需要存储的 token 数据 
    }, app.config.jwt.secret);
    
  2. JWT校验
    ctx.app.jwt.verify(token, ctx.app.config.jwt.secret) 
    // 返回一个对象,user属性为当时存储的数据, iat 属性为过期时间
    

定点排坑

  1. JsonWebTokenError: invalid token
    // 解决方案
    const token = ctx.headers.authorization ? ctx.headers.authorization.split(' ')[1] : '';
    
    原因解析: 在 token 一般附请求头 authorization 字段上提交至服务端。它会在 token 前面添加标识字符,因此服务端时机接收到的数据大概长这样:Baerer xxxxxxx.xxxxxx.xxxx。因此,我们只需要移除掉前面的字符即可被 JWT 识别。
  2. JsonWebTokenError: invalid signature
    // 解决方案
    app.jwt.sign({ 
        username: data, // 必须字段
        // 其他标识信息 
    }, app.config.jwt.secret );
    
    原因解析: 翻译过来就是无效标识符,那么只要找到标识符,在生成的时候添加即可。

抽离封装

将上面的代码拓展一下,封装为权限鉴定工具类

// auth.utils.js 
'use strict'; 
module.exports = { 
    async authJWT(ctx, next) { 
        const token = ctx.headers.authorization ? ctx.headers.authorization.split(' ')[1] : ''; 
        try { 
            ctx.app.jwt.verify(token, ctx.app.config.jwt.secret); 
            // 在路由上不用添加(会报 next() 重复异常),非路由需要 
            //   if(typeof next === 'function'){
           //        await next();
            //   }
        } 
        catch (error) { 
            ctx.body = {
                code: 400, 
                data:{ token }, 
                msg: 'fail' 
            }; 
        console.log(error); 
        return; 
        } 
    }, 
    async genarateJWT(ctx, secret, usrName) { 
        return app.jwt.sign( { username: usrName, // 其他标识信息 }, secret ); 
    }, 
};

// 

参考链接
1.egg-jwt(github)
2.JsonWebTokenError: invalid token
3.JsonWebTokenError: invalid signature