How to handle Refesh-Tokens with GoogleApis for NodeJS Client?

Viewed 306

I'm looking at the following documentation: https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens

Especially this part:

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);
});

What I don't understand is why I should store the refresh-token in a database. Is it due to that the refresh-token is only provided to me on the first authorization? But even so, shouldn't that mean that this part:

oauth2Client.setCredentials({
  refresh_token: `STORED_REFRESH_TOKEN`
});

should replace the comment above (// store the refresh_token in my database!)? A.K.A:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    oauth2Client.setCredentials({
  refresh_token: tokens.refresh_token
  });
});

This due to Google's statement in the documentation: "This library will automatically use a refresh token to obtain a new access token if it is about to expire".

What I want to build is an application where people login with their Google-account and then can use several analytics tools I build utilizing f.e Google-analytics API.

I've managed via the documentation to set a valid access-token, but I'm really interested in this topic and really want to learn the refresh-part but have a really hard time wrapping my head around it. If someone could help me understand, I would be really greatful. If not, could someone point me to a great explanation of this (for nodejs) elsewhere? :)

1 Answers

Refresh tokens exist to keep a balance between security and user experience. Access tokens should be short-lived (read more about access token lifetime), just in case a malicious attacker gets access to it. Without Refresh tokens, you will need to request user authorization each time.

Refresh tokens should be stored in a safe place

Save refresh tokens in secure long-term storage and continue to use them as long as they remain valid.

When you call oauth2Client.setCredentials you are initializing the SDK, so it can use the refresh token to fetch a new access token, but the SDK is not storing the refresh token in any long-term storage. That's your application responsibility.

Take into account, a Refresh token can be revoked too, in case it was leaked, or has not been used for six months (for Google APIs). Also, rotating a refresh token regularly is a good security practice.

It's your application responsibility to handle that part too, you can read more about Refresh token expiration here

Related