egg.js jwt 幾步實現加解密


 

1. 安裝

npm install --save egg-cors egg-jwt

2. 配置

// config/config.default.js
config.jwt = { secret: '123456', enable: true, // default is false match: '/jwt', // optional expiresIn: '24h', }; // 安全配置 (https://eggjs.org/zh-cn/core/security.html config.security = { csrf: { enable: false, ignoreJSON: true, }, domainWhiteList: [ 'http://localhost:8080' ], // 允許訪問接口的白名單 }; // 跨域配置 config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', };

3. 路由

'use strict';

module.exports = app => {
  const { router, controller: { login }, middleware } = app;
  const jwt = middleware.jwtCheck(app.config.jwt);

  router.post(`login`, login.index); // 登錄得到 token 等用戶信息
  router.get(`login/test`, jwt, login.test); // 解碼驗證
};

4. 登錄得到 token 等用戶信息

請求(post):http://localhost:7001/login

// controller/login.js
'use strict';

const Controller = require('../core/baseController');
class HomeController extends Controller {

  // 登錄,驗證,成功發token
  async index() {
    const { ctx, app } = this;
    const req = ctx.request.body;
    const errArr = app.validator.validate({
      username: 'string',
      password: 'string',
    }, req);

    if (errArr) { // 非空驗證
      this.$error(JSON.stringify(errArr));
      return;
    }

    try {
      // 查庫驗證
      const data = await ctx.model.User.findAll({ where: req });

      if (data.length > 0) {

        const user = data[0];
        const { jwt: { secret, expiresIn } } = app.config;
        // 需傳 secret 過期時間
        const token = app.jwt.sign({
          id: user.id,
        }, secret, {
          expiresIn,
        });

        this.$success({ token, user });

      } else {
        this.$error('用戶名或密碼不正確');
      }
    } catch (err) {
      this.$error(err);
    }

  }

  async test() {
    const { ctx } = this;
    ctx.body = { code: 201, msg: '驗證成功', data: ctx.state.user };
    console.log('\n\n user +++', ctx.state.user);
  }

}

module.exports = HomeController;

5. 解碼驗證

請求(get):http://localhost:7001/login/test

// middleware/jwtCheck.js
'
use strict'; module.exports = options => { return async function jwtErr(ctx, next) { const headerStr = ctx.request.header.authorization; if (headerStr) { try { // 解碼token,需傳加密時的 secret const decode = ctx.app.jwt.verify(headerStr, options.secret); ctx.state.user = decode; // 信息存一下,這步很重要,業務里要用 await next(); } catch (error) { ctx.status = 401; // 翻譯錯誤碼 let message = error.message; ctx.body = { code: -1, msg: message, }; return; } } else { ctx.status = 401; ctx.body = { code: -1, msg: 'no header token', }; return; } }; };

 

以上幾步,用 egg-jwt  實現登錄獲取 token ,然后傳 token 驗證身份,並存在 ctx.state.user  為后面業務里用

 

 

 

.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM