Question

I am trying to understand how the authorization(particular the refresh tokens) working for nodejs Google Drive API.

Here it's the code from https://github.com/google/google-api-nodejs-client.

    oauth2Client.credentials = {
      access_token: 'ACCESS TOKEN HERE',
      refresh_token: 'REFRESH TOKEN HERE'
    };

    client
      .plus.people.get({ userId: 'me' })
      .withAuthClient(oauth2Client)
      .execute(callback);

General Question: How does refresh tokens actually work together with access token?

Background: As what I interpret is that each access token has a limited timespan (~1 hr). So when a user FIRST connect to my server (which the server provides mechanism for user authentication), the server receives limited-life access token and ONE-TIME refresh token. After 1 hour, the access token is expired.

Specific question: Here comes to the key questions. After the expiration, my server stills send request to the Google Drive Api with the EXPIRED access token and refresh token (Server uses session to store those values). Will this still be able to access the content in Google Drive? What I am guessing is that the nodejs lib + google drive api is SMART enough to detect the access token is expired & refresh token is identified & api replace the expired access token with new access token blindly (like server does not need to do anything; just google drive api). Will the api response the server with a new Access Code?

I need to figure this out because I need to organize my code in Nodejs effectively.

Thanks!

Was it helpful?

Solution

Yes.

The Node.js API client will detect access token errors and automatically refresh the token.

You can see this in the source:

var hasAuthError = res.statusCode == 401 || res.statusCode == 403;
// if there is an auth error, refresh the token
// and make the request again
if (!opt_dontForceRefresh && hasAuthError && credentials.refresh_token) {
  // refresh access token and re-request
  that.refreshToken_(credentials.refresh_token, function(err, result) {
    if (err) {
      opt_callback && opt_callback(err, null, null);
    } else {
      var tokens = result;
      tokens.refresh_token = credentials.refresh_token;
      that.credentials = tokens;
      that.request(opts, opt_callback, true);
    }
  });
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top