1
votes

So I am working on a Node.js app that will poll Google Analytics api ever x amount of seconds. I have setup a "Service Account", and converted the p12 key to a .pem file. Initial setup looks something like this:

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);
});

I had not realized that the initial tokens have an expiration date of 1 hour; however the tokens I receive look like this:

{
  access_token: ...,
  token_type: 'Bearer',
  expiry_date: NaN,
  refresh_token: 'jwt-placeholder
}

My question is, once I get that 401 invalidCredentials error, do I simply just re-authorize to get a new access token to be able to poll from Google Analytics? I am new to JWT, and this seems like it will be authorizing way too many times. Is there a limit to this?

For reference, I am using the Google API Node.js Client Library

1

1 Answers

4
votes

Yes, just rebuild authClient as you did the first time. Service Accounts don't have refresh tokens like other OAuth flows, you just rebuild the authentication when the current access token expires.