zoukankan      html  css  js  c++  java
  • egg.js的egg-jwt生成token做成中间件

    做egg.js项目时想生成token,用egg-jwt插件最好了,但是不小心很容易踩到坑。主要主要几点:

    1、把csrf关掉  

    config.security = {
        csrf: {
          enable: false,
          ignoreJSON: true
        }
    };

    2、验证token写成中间件

    3、前端交互时在headers传token给后台  

    headers: {'Authorization': `${sessionStorage.getItem('token')}`} //登录时把后台传过来的token传到sessionStorage里
    注意:千万不要加Bearer,
    写成headers: {'Authorization': `Bearer ${sessionStorage.getItem('token')}`}会报"message": "invalid token"错误。

    以下是大概步骤:

    1、安装egg省略,可参考:https://www.cnblogs.com/zzwlong/p/13555926.html

    2、安装egg-jwt:

    npm install egg-jwt --save 或 cnpm install egg-jwt --save

    3、配置jwt

    1) configplugin.js
    jwt: { enable:
    true, package: 'egg-jwt', },

    2) configconfig.default.js
    config.jwt = { //jwt配置项 secret: "123456" }

    4、扩展那里的helper.js加添加生成token的方法

    appextendhelper.js
    //
    生成token getToken(value) { return this.app.jwt.sign(value, this.app.config.jwt.secret); }

    5、在egg后台登录页引入生成token的方法,并在authorization设置token  

    'use strict';
    
    const Controller = require('egg').Controller;
    
    class LoginController extends Controller {
        async login() {
        const { ctx, app } = this;
        const { username,password } = ctx.request.body;
        const token = ctx.helper.getToken();
        ctx.set({'authorization':token})
        const result = await ctx.service.login.login(username,password);
        ctx.body = result;
        }
    }
    
    module.exports = LoginController;

    6、封装验证token的中间件

    //middleware/jwtErr.js
    module.exports = (options) => {
      return async function jwtErr(ctx, next) {
          const token = ctx.request.header.authorization;
          let decode = '';
          if (token) {
            try {
              // 解码token
              decode = ctx.app.jwt.verify(token, options.secret);//验证token
              await next();
              console.log('decode======>',decode);
            } catch (error) {
              ctx.status = 401;
              ctx.body = {
                message: error.message,
              };
              return;
            }
          } else {
            ctx.status = 401;
            ctx.body = {
              message: '没有token',
            };
            return;
          }
        };
    }

    7、postman请求,请求时headers记得token前不要加Beare和空格

    差不多就是这样了,网上好多用egg-jwt的,但好多都是前端请求接口时headers加token时加Bearer 的,我试了会报"message": "invalid token"错误,得去掉。

    by the way 中间件可以在configconfig.default.js这个文件配置

  • 相关阅读:
    打破国外垄断,开发中国人自己的编程语言(1):实现可以解析表达式的计算器
    the best way to get the OBJECTID OID name in arcpy?
    arcpy 自定义工具可选参数留空时的处理
    Word 显示隐藏图片
    删除Word表格后的一张空白页
    如何查看别人申请加群的历史记录
    OpenLayers v2 热力图插件
    IDEA JRebel热部署插件安装使用
    Lombok的@Data等注解无效
    CAP理论/AP架构/CP架构
  • 原文地址:https://www.cnblogs.com/zzwlong/p/13631708.html
Copyright © 2011-2022 走看看