Refresh token of google api do not work properly in nodejs

后端 未结 2 1844
死守一世寂寞
死守一世寂寞 2021-01-03 03:21

I am using google api nodejs , I try to get data from google Anaytics

var google = require(\'googleapis\');
var OAuth2Client = google.auth.OAuth2;
var CLIENT         


        
相关标签:
2条回答
  • 2021-01-03 04:02

    access_token have expire time is 1 hour. You must refresh access_token when it's expired.

    oauth2Client.refreshAccessToken(function(err, tokens) {
      // your access_token is now refreshed and stored in oauth2Client
      // store these new tokens in a safe place (e.g. database)
    });
    

    Can you find it here

    0 讨论(0)
  • 2021-01-03 04:09

    No need to explicitly refresh token, when access_token expired. Oauth2 Client will refresh token automatically and the request is replayed, provided when you get refresh_token in first authorization, set this refresh_token in OAuth2 client credentials as shown in the following code

    const {tokens} = await oauth2Client.getToken(code)
    oauth2Client.setCredentials(tokens);
    

    Still, you want to manually refresh the access_token, then use the following code.

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

    OR

    oauth2Client.refreshAccessToken((err, tokens) => {
      // your access_token is now refreshed and stored in oauth2Client
      // store these new tokens in a safe place (e.g. database)
    });
    

    References:

    1. https://github.com/googleapis/google-api-nodejs-client/blob/c00d1892fe70d7ebf934bcebe3e8a5036c62440c/README.md#making-authenticated-requests
    2. https://github.com/googleapis/google-api-nodejs-client/blob/c00d1892fe70d7ebf934bcebe3e8a5036c62440c/README.md#manually-refreshing-access-token
    3. https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens
    0 讨论(0)
提交回复
热议问题