如何刷新 Google Analytics Reporting API v3 的访问令牌

vic*_*jia 1 google-analytics google-api node.js jwt google-api-nodejs-client

因此,我正在开发一个 Node.js 应用程序,它将每隔x几秒轮询一次 Google Analytics api。我已经设置了一个“服务帐户”,并将p12密钥转换为.pem文件。初始设置看起来像这样:

var authClient = new google.auth.JWT(authData.serviceEmail, authData.keyFile, null, authData.scope, '');

authClient.authorize(function(err, tokens) {
  if (err) {
    winston.log('error', 'Error authorizing with GA', {error: err});
    return;
  }

  setInterval(function() {
    analytics.data.realtime.get({
      'auth': authClient,
       ...
    }, function (err, body) {
        // getting 401 error here
    })
  }, 20000);
});
Run Code Online (Sandbox Code Playgroud)

我没有意识到初始代币的有效期为 1 小时;但是我收到的令牌如下所示:

{
  access_token: ...,
  token_type: 'Bearer',
  expiry_date: NaN,
  refresh_token: 'jwt-placeholder
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,一旦收到该401 invalidCredentials错误,我是否只需重新授权即可获取新的访问令牌以便能够从 Google Analytics 进行轮询?我是 JWT 的新手,这似乎会授权太多次。这有限制吗?

作为参考,我正在使用Google API Node.js 客户端库

Jay*_*Lee 5

是的,只需像第一次一样重建 authClient 即可。服务帐户不像其他 OAuth 流那样具有刷新令牌,您只需在当前访问令牌过期时重建身份验证。