基於token的身份驗證在nodejs中的應用


token驗證大致流程

  • 客戶端使用用戶名跟密碼請求登錄
  • 服務端收到請求,去驗證用戶名與密碼
  • 驗證成功后,服務端會簽發一個 Token,再把這個 Token 發送給客戶端
  • 客戶端收到 Token 以后可以把它存儲起來,比如放在 Cookie 里或者 Local Storage 里
  • 客戶端每次向服務端請求資源的時候需要帶着服務端簽發的 Token
  • 服務端收到請求,然后去驗證客戶端請求里面帶着的 Token,如果驗證成功,就向客戶端返回請求的數據

代碼實踐

1、用戶名密碼校驗成功后,生成token並返回

// 登錄成功后返回該用戶信息
        const result = await this.UserService.login(email, newPas);
        if (result.length > 0) {
          // 校驗成功,生成token並返回
          // expiresIn過期時間支持單位 days, hours, etc,例如 "2 days", "10h", "7d",默認使用毫秒單位 “120”或者"120ms"
          const token = this.app.jwt.sign({ userid: result[0].userid, username: result[0].username },
            this.app.config.jwt.secret, { expiresIn: '1h' });
          response = this.ResultResponse.createBySuccessData(token);
        } else {
          response = this.ResultResponse.createByErrorMsg('密碼輸入不正確');
        }

2、客戶端拿到token后將token存儲到cookie中,在請求需要權限的接口將token通過header的形式攜帶過去

// 將token存儲到cookie中
          const token = response.data
          Cookies.set('token', token)


getMemberProfile: () => {
    return fetch(`${apiUrl}/api/v2/user/profile`, {
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        Authorization: `Bearer ${Cookies.get('token')}`
      }
    })
      .then(response => response.json())
      .then(response => {
        if (response.code === 0) {
          return response.data
        }
      })
  },

3、編寫一個用於校驗token的中間件,如果過期或者不合法則跳轉到登錄頁面

module.exports = app => {
  return async function verifyToken(ctx, next) {
    const authorization = ctx.request.header.authorization;
    if (authorization) {
      try {
        // 通過app.jwt.verify驗證token合法性
        // iat: 1581434960  token簽發時間   exp: 1581438560   token過期時間
        const token = authorization.split(' ')[1];
        app.jwt.verify(token, app.config.jwt.secret);
        // 只有在通過之后才會執行下一個中間件
        await next();
      } catch (error) {
        ctx.body = ctx.response.ResultResponse.createByErrorCodeMsg('10001', error.message);
      }
    } else {
      ctx.body = ctx.response.ResultResponse.createByErrorCodeMsg('10001', 'not allow');
    }
  };
};

4、在路由處使用該中間件

module.exports = app => {
  const verifyToken = app.middleware.verifyToken(app);
  app.router.post('/api/v2/post/add', verifyToken, app.controller.v2.postsController.postsAdd);
};

5、從token中獲取用戶信息id,然后在需要的地方調用該方法

  getUserid() {
    const authorization = this.ctx.request.header.authorization;
    const token = authorization.split(' ')[1];
    const userid = this.app.jwt.verify(token).userid;
    return userid;
  }

參考閱讀


免責聲明!

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



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