egg-jwt

1.0 jwt思路

  1. 用戶輸入用戶名和密碼登陸,若是用戶名和密碼正確的話,使用 jsonwebtoken.sign() 生成 token,並返回給客戶端。
  2. 客戶端將token存儲在本地存儲,在每次的 HTTP 請求中,都將 token 添加在 HTTP Header Authorazition: Bearer token 中。
  3. 而後後端每次去驗證該token的正確與否。只有token正確後才能訪問到對應的資源。

githubgit

1.1 安裝依賴

cnpm install jsonwebtoken --save
複製代碼

1.2 配置jwt的secret(密鑰)

config\config.default.jsgithub

config.jwt = {
    secret: '我是密鑰',
  };
複製代碼

1.3 用戶登陸,根據userId存儲jwt

app\controller\home.jsweb

async jwt() {
    const { ctx } = this;
    const userId = '123456';
    const result = await ctx.service.jwt.signJwt(userId);
    const data = await ctx.service.jwt.verifyJwt(result);
    ctx.body = data;
  }
複製代碼

1.4 sign簽名

  1. 第一個參數,要加密的數據
  2. 第二個參數,加密的密鑰
  3. 第三個參數,對象,過時時間
async signJwt(userId) {
    const { ctx } = this;
    const token = jwt.sign({ userId }, this.config.jwt.secret, {
      expiresIn: 60,
    });
    return token;
  }
複製代碼

1.5 verify檢驗`

async verifyJwt(token) {
    const { ctx } = this;
    try {
      let hasToken = false;
      const userId = jwt.verify(token, this.config.jwt.secret).userId;
      console.log(userId);
      if (userId == '123456') {
        hasToken = true;
        return hasToken;
      }
      return hasToken;

    } catch (err) {
      throw (err);
    }
  }
複製代碼

1.6 效果

本站公眾號
   歡迎關注本站公眾號,獲取更多信息