eggjs入門系列——使用jwt

寫在前面

有關於jwt的相關介紹,請各位本身百度,自行腦補,本文主要介紹在eggjs中如何使用jwtnode

目前使用最普遍jwt的node庫爲Json Web Token,倉庫地址爲:github.com/auth0/node-…git

安裝

初始化eggjs項目後,進入項目目錄下,執行如下命令:github

npm install jsonwebtoken
複製代碼

使用

在service目錄下,新建token.js文件:web

'use strict';

const Service = require('egg').Service;
const jwt = require('jsonwebtoken');

class TokenService extends Service {
  async signJwt(_id) {
    return jwt.sign({
      data: {
        _id,
      },
      exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7),
    }, 'this is secert key, you can replace it!');
  }

  async decodeJwt(token) {
    try {
      return jwt.verify(token, 'this is secert key, you can replace it!');
    } catch (err) {
      return err;
    }
  }
}

module.exports = TokenService;
複製代碼
相關文章
相關標籤/搜索