Search code examples
google-api-nodejs-clientgoogle-my-business-api

Current method to get new access token from refresh token


I see some questions about this with solutions that seem to be deprecated in the Google APIs Node.js Client OAuth API (e.g., this and this).

There's no documentation I can see regarding using the refresh token to get a new access token (docs section). In an issue from early 2017, someone mentions getting off the oauth2Client.credentials property, but it looks like that's within a call to one of the other APIs wrapped in the package.

In my use case, I'm querying the Google My Business (GMB) API, which is not wrapped in there, but I'm using the OAuth piece of this package to authenticate and get my tokens.

My request to the GMB API (using the request-promise module), looks something like this:

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) {
    // ...
  });
}

I don't think I can pass the oauth2Client into the headers for authorization like in the issue response. Is there a way to directly request a new access_token given that I have my refresh token cached in my app?

Update: Solved! Thanks to Justin for the help. Here's what my working code is looking like:

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

Solution

  • If you have an existing oauth2 client, all you need to do is call setCredentials:

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

    On the next call that goes through the client, it will automatically detect there is no access token, notice the refresh token, and go snag a new access token along with it's expiration date. I outlined some docs and code around this in the issue you opened up on GitHub :P

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

    Hope this helps!