Ad

Google API - Listen For Expired Token With Library

I've setup oauth2 flow to use google API with refresh_token.

I'm using nodejs library to issue requests. I store the complete token (refresh + access) in the database and pass it to the library. Now every time when the access token expires, the library updates it automatically using the provided refresh_token.

The question is: since the library automatically updates the token when needed, how can I get that updated refresh token so I can pass it in the subsequential calls?

I understand that I can issue a "refreshToken" call myself but as long as the library does that automatically when needed can I just access the updated token right away?

I guess I saw something like that in the docs (to set a kind of listener on token refresh?) but I can't find it anymore.

Ad

Answer

Finally found the part of the doc again where it shows how to listen for token expiration:

Handling refresh tokens

Access tokens expire. This library will automatically use a refresh token to obtain a new access token if it is about to expire. An easy way to make sure you always store the most recent tokens is to use the tokens event:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});
Ad
source: stackoverflow.com
Ad