invalid_grant error trying to refresh access token for googleapis

Viewed 1266

We use the googleapis for our web app and store and manage the access token and refresh token to our database. When we refresh the access token of users using refresh token, rarely we had the GaxiosError: invalid_grant.

Now, we use the google api nodejs client[ https://github.com/googleapis/google-api-nodejs-client ]. We store the access token and the refresh token to our database for each user and they are updated by bellow logic per 6 hours.

import { google } from 'googleapis';

// create oauth2client for google apis
const oAuth2Client = new google.auth.OAuth2(client_secret, client_id, redirect_uri);

// set current access token and refresh token (==current_tokens)
oAuth2Client.setCredentials(current_tokens);

// refresh access token and refresh token
// new_token contains access_token and refresh_token
const new_token = await oAuth2Client.refreshAccessToken();

// store the new access token and new refresh token to database
...

Does anyone know what may be causing GaxiosError: invalid_grant? I'm getting the feeling that it may be due to the refresh token being updated every 6 hours.

Additional Info

the setting of generating auth url

const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: GOOGLE_APIS_SCOPE, // GOOGLE_APIS_SCOPE contains scopes
        prompt: 'consent',
      });
1 Answers

There are a number of reasons why a refresh token will expire If we check the documentation for Oauth2 You will find a list of them here.

  • The user has revoked your app's access.
  • The refresh token has not been used for six months.
  • The user changed passwords and the refresh token contains Gmail scopes.
  • The user account has exceeded a maximum number of granted (live) refresh tokens.
  • The user belongs to a Google Cloud Platform organization that has session control - policies in effect.
  • A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

Currently the most common reason would be that your application is not set to production if its still in testing then your refresh token will expire in a week.

You mention that its stored in the database every six hours. I would double check if you are refreshing the access token every six hours and that it does return a new refresh token each time that you are in fact updating the database with the most current refresh token otherwise you may be reaching the "maximum number of granted (live) refresh tokens"

Related