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)
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 theaccess_token
and as @zoellner suggested, addingexpiry_date: true
solves this problem. However, in the documentation (README.md
) it says: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.