【问题标题】:Refresh Oauth token after certain time in Node API在 Node API 中的一定时间后刷新 Oauth 令牌
【发布时间】:2019-05-18 05:07:43
【问题描述】:

我已经向客户端公开了一个基于 Express 构建的 REST api,但是我的 api 正在调用外部 API,这需要每 60 分钟轮换一次 oauth 令牌,而且我不期望来自客户端的令牌,我必须在调用外部 api 之前自己生成它每 60 分钟并将其传递给外部 api。我使用 setTimeOut 函数使用以下代码 但我正在寻找其他更好的方法来刷新所见背后的令牌。请帮助我

//Refresh Token logic

     async refreshToken() {
            try {
                let token = 'xyz-sbdkd'//from api;
                // set token in global variable
                process.env.TOKEN = token

                setTimeout(() => {
                    this.refreshToken();
                }, 59 * 60000);//this will be 59 minutes
            } catch (err) {
                setTimeout(() => {
                    this.refreshToken();
                }, 3000);
            }
        }

【问题讨论】:

    标签: node.js express oauth refresh-token


    【解决方案1】:

    正常的做法是处理401Unauthorized错误,就是token过期时使用的。

      let axiosRequest = async (options) => {
        try {
          await axios(options) // try to call
        } catch (err) {
          if (err.status === 401) { // token is expired
            let accessToken = await getNewAccessToken(refreshToken) // call the refresh token endpoint to get a new access token
            options.headers = {Authorization : `Bearer ${accessToken}`} // set the new access token to initial petition
            return await axiosRequest(options) // call again with new token
          }
          throw err
        }
      }
    

    使用 axios 原生拦截器可以找到更优雅的方法,但无法尝试: https://gist.github.com/mkjiau/650013a99c341c9f23ca00ccb213db1c

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2017-11-20
      相关资源
      最近更新 更多