google-api-nodejs-client: Refresh token automatically on HTTP 401 or 403 response?

I’m using the API (v1.0.10) in the following way:

    var oauth2Client = new OAuth2(getGoogleCredentials().clientId, getGoogleCredentials().secret);
    oauth2Client.setCredentials({
      access_token: user.services.google.accessToken,
      refresh_token: user.services.google.refreshToken
    });
    calendar.events.list({
        calendarId: 'primary',
        auth: oauth2Client
      }, ...);

When my token is expired I get an HTTP 401 back from the server. However, I’d expect the library to automatically refresh my token and make the request again. It doesn’t.

I figured out that a workaround is to add the expiry_date when calling setCredentials, e.g.

oauth2Client.setCredentials({
      access_token: user.services.google.accessToken,
      refresh_token: user.services.google.refreshToken,
      expiry_date: user.services.google.expiresAt
    });

But this isn’t mentioned in the docs. I’d expect expiry_date to be optional and the API to auto refresh the token.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 25 (7 by maintainers)

Most upvoted comments

Cheers for the snappy response! 🍻

Greetings! The event based approach is new, and was added after this post was originally answered 😃 . Both ways are fine honestly. The nice thing about using the event is that you get notified not only when the refresh_token changes, but also when the access_token is refreshed. The tokens returned here should return the expiry_date.

As this issue is not closed yet, I thought I’d ask for an update on the matter. As discussed before, the token is not automatically refreshed, when sending both the refresh_token and the access_token and as @zoellner suggested, adding expiry_date: true solves this problem. However, in the documentation (README.md) it says:

You can start using OAuth2 to authorize and authenticate your requests to Google APIs with the retrieved tokens. If you provide a refresh_token and the access_token has expired, the access_token will be automatically refreshed and the request is replayed.

So you might want to update that.

I ran into a similar issue. What works for me is to set expiry_date to true when setting the credentials and I don’t have a date availble. This will force a token refresh, you can then store the client’s expiry_date after using it.

    oauth2Client.setCredentials({
      access_token: user.google.accessToken,
      refresh_token: user.google.refreshToken,
      expiry_date: true
    });