user3203518
user3203518

Reputation: 51

NodeJS Google Api client: how do I know the access token is expired?

I am working on Nodejs Google Api client Oauth process. I follow what the code example for oauth, https://github.com/google/google-api-nodejs-client/blob/master/examples/oauth2.js.

I have one question. How do I check if the access token is expired and how do I use the refresh token to get another access token again?

To be more specific, let's say get access to google+ user profile, so I use the access token to get user profile:

getAccessToken(oauth2Client, function() {
    // retrieve user profile
    getUserProfile(client, oauth2Client, 'me', function(err, profile) {
      if (err) {
        console.log('An error occured', err);
        return;
      }
      console.log(profile.displayName, ':', profile.tagline);
    });
  });

In addition, in the client side of the application(backbonejs), if I am attempting to use google api JS client to access the google drive api (not google plus), I am not sure if I can use the access token I get from server side of the application (nodejs) or I have to do another OAuth using google api JS client.

Upvotes: 5

Views: 4233

Answers (1)

Prisoner
Prisoner

Reputation: 50731

Best practice to determine if an access token is expired is to try and use it. Although the bundle returned includes the *expires_in* parameter, indicating the number of seconds until the access token expires, this isn't reliable, since it may be revoked and replaced for other reasons at any time.

The procedure then typically is

  1. Attempt to make the call using the access token
  2. If you get an "unauthorized" response, use the referesh token to get a new access token. If this fails, your permission has been revoked
  3. Attempt to make the call using the new access token again

If you're using the library to do other Google API calls - this will be handled for you automatically.

Upvotes: 7

Related Questions