09_微信小程式之無感知重新整理token

andr_gale發表於2020-12-14

09_微信小程式之無感知重新整理token

一.介面呼叫憑證token

微信小程式授權登入之後,會成生成token返回給客戶端,客戶端取得token之後,作為後續一系列介面的呼叫憑證,然後,伺服器返回給客戶端的token會有一個有效期,token一但過期,就會導致客戶端後續的介面呼叫失敗,因此,在呼叫介面之前,我們需要保證token是有效的,這樣才能保證客戶端的功能不會因為token過期而導致異常

二.微信授權登入、token合法性及有效性校驗

關於微信授權登入,可參考06_基於koa實現微信小程式授權登入流程

token合法性及有效性校驗

const Router = require('koa-router')
const router = new Router()
const { verifyToken } = require('../../../../utils/utils')
const User = require('../../../../model/user')

router.post('/api/v1/member/verify', async (ctx, next) => {
    const token = ctx.request.header.token
    //驗證token是否過期
    const decoded = verifyToken(token)
    
    const res = await User.findByOpenID(decoded.openid)
    if(!res) {
        //使用者不存在
        throw new global.errors.UserNotFoundException()
    }

    ctx.body = {
        code: 0,
        msg: "token有效"
    }
})

module.exports = router
const jwt = require('jsonwebtoken');

const verifyToken = function(token, secret) {
    let decoded
    try {
        decoded = jwt.verify(token, 'com_aykj_gale');
    } catch(error) {
        let err = new global.errors.ForbiddenException()
        if(error.name == 'TokenExpiredError') {
            err.msg = 'token已過期'
            err.errorCode = 10006
        } else {
            err.msg = 'token不合法'
            err.errorCode = 10005
        }
        throw err
    }
    
    return decoded
}
/api/v1/member/code2token: 登入獲取token
/api/v1/member/register: 註冊
/api/v1/member/verify: token合法性及有效性校驗
/api/v1/member/member_index: 獲取使用者資訊,後續會基於此介面,實現token的無感知重新整理

三.微信小程式中請求介面

// /project_directory/config.js
const serverUrl = 'http://192.168.1.111:3000'

const config = {
  code2token: `${serverUrl}/api/v1/member/code2token`,
  register: `${serverUrl}/api/v1/member/register`,
  verify: `${serverUrl}/api/v1/member/verify`,
  memberIndex: `${serverUrl}/api/v1/member/member_index`
}

module.exports = config
// /project_directory/utils/http-service.js
class HttpService {
  constructor(){}

  get(url, params, headers) {
    if(!headers) {
      headers = {}
    }
    return this._request(url, 'GET', params, headers)
  }

  postJson(url, params, headers) {
    if(!headers) {
      headers = {}
    }
    headers['content-type'] = 'application/json'
    return this._request(url, 'POST', params, headers)
  }

  postForm(url, params, headers) {
    if(!headers) {
      headers = {}
    }
    headers['content-type'] = 'application/x-www-form-urlencoded'
    return this._request(url, 'POST', params, headers)
  }

  _request(url, method, params, headers) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        method: method,
        data: params,
        header: headers,
        complete: function(res) {
          var errMsg = res.errMsg //request:ok;request:fail
          if(errMsg != "request:ok") {
            var reason = {
              code: -1,
              msg: "請求超時"
            } 
            reject(reason)
          } else {
            var resData = res.data
            var resDataCode = resData.code
            if(resDataCode != undefined) {
              if(resDataCode == 0) {
                resolve(resData)
              } else {
                reject(resData)
              }
            } else {
              var reason = {
                code: -1,
                msg: resData
              }
              reject(reason)
            }
          }
        }
      })
    })
  }
}

module.exports = HttpService
// /project_directory/http/request-center.js
import HttpService from "../utils/http-service"
import config from "../config"

const tokenKey = "token"

class RequestCenter {
  constructor() {
    this.httpService = new HttpService()
  }

  register(params, headers) {
    return this.httpService.postJson(config.register, params, headers)
  }

  code2token(params, headers) {
    return this.httpService.postJson(config.code2token, params, headers)
  }

  verifyToken(params, headers) {
    return this.httpService.postJson(config.verify, params, headers)
  } 

  memberIndex(params, headers) {
    return this.httpService.postJson(config.memberIndex, params, headers)
  }

  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        complete: function(res) {
          if(res && res.code) {
            resolve(res.code)
          } else {
            reject({
              code: -1,
              msg: "wx.login 失敗"
            })
          }
        }
      })
    })
  }
  
}

const requestCenter = new RequestCenter()

module.exports = requestCenter
// /project_directory/pages/index/index.js
const app = getApp()

Page({
  data: {
    
  },

  onLoad: async function(res) {
    var token = wx.getStorageSync('token')
    if(!token) {
      wx.reLaunch({
        url: '/pages/auth/auth',
      })
    } else {
      var headers = {}
      headers["token"] = wx.getStorageSync('token')
      await getApp().global.requestCenter.memberIndex({}, headers)
    }
  }
})

四.無感知重新整理token

在這裡插入圖片描述

// /project_directory/http/request-center.js
import HttpService from "../utils/http-service"
import config from "../config"

const tokenKey = "token"

class RequestCenter {

  ...

  memberIndex(params, headers) {
   return this._verify(params, headers, () => {
      return this.httpService.postJson(config.memberIndex, params, headers)
    })
  }

  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        complete: function(res) {
          if(res && res.code) {
            resolve(res.code)
          } else {
            reject({
              code: -1,
              msg: "wx.login 失敗"
            })
          }
        }
      })
    })
  }
  
  _verify(params, headers, fun) {
    if(headers && headers[tokenKey]) {
      return new Promise((resolve, reject) => {
        //驗證token是否過期
        this.verifyToken(params, headers).then((res) => {
          //token未過期,繼續上一次請求
          fun().then((res) => {
            resolve(res)
          }, (reason) => {
            reject(reason)
          })
        }, (reason) => {
          var code = reason.code
          if(code == 10006) {
            //token過期,重新整理token,繼續上一次請求
            this.wxLogin().then((res) => {
              this.code2token({code:res}, {}).then((res) => {
                var token = res.token
                wx.setStorageSync('token', token)
                headers[tokenKey] = token
                fun().then((res) => {
                  resolve(res)
                }, (reason) => {
                  reject(reason)
                })
              }, (reason) => {
                reject(reason)
              })
            }, (reason) => {
              reject(reason)
            })
          } else {
            reject(reason)
          }
        })
      })
    } else {
      return fun()
    }
  }
  
}

const requestCenter = new RequestCenter()

module.exports = requestCenter

相關文章