从刷新令牌获取新访问令牌的当前方法

时间:2018-05-08 22:14:09

标签: google-api-nodejs-client google-my-business-api

我在Google API Node.js客户端OAuth API(例如thisthis)中似乎已弃用的解决方案中有一些问题。

我没有关于使用刷新令牌获取新访问令牌(docs section)的文档。 In an issue from early 2017,有人提到要离开oauth2Client.credentials媒体资源,但看起来这是在调用包裹中包含的其他API之一的内容。

在我的使用案例中,我查询了Google My Business(GMB)API,该API未包含在其中,但我使用此程序包的OAuth部分进行身份验证并获取我的令牌。

我对GMB API的请求(使用request-promise模块)看起来像这样:

function getLocations () {
  return request({
    method: 'POST',
    uri: `${gmbApiRoot}/accounts/${acct}/locations:batchGet`,
    headers: {
      Authorization: `OAuth ${gmbAccessToken}`
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    // ...
  });
}

我认为我不能像问题回复一样将oauth2Client传递到标题中进行授权。有没有办法直接请求新的access_token,因为我的应用程序中有我的刷新令牌?

更新:解决了!感谢Justin的帮助。这是我的工作代码的样子:

oauth2Client.setCredentials({
  refresh_token: storedRefreshToken
});

return oauth2Client.refreshAccessToken()
.then(function (res) {
  if (!res.tokens && !res.credentials) {
    throw Error('No access token returned.');
  }

  const tokens = res.tokens || res.credentials;

  // Runs my project-level function to store the tokens.
  return setTokens(tokens);
});

1 个答案:

答案 0 :(得分:1)

如果您有现有的oauth2客户端,您需要做的就是致电setCredentials

oauth2client.setCredentials({
  refresh_token: 'REFRESH_TOKEN_YALL'
});

在通过客户端的下一个呼叫中,它将自动检测到没有访问令牌,注意刷新令牌,并随着新的访问令牌的到期日期一起阻止它。我在GitHub上打开的问题中概述了一些文档和代码:P

https://github.com/google/google-api-nodejs-client/pull/1160/files

希望这有帮助!

相关问题