2016-05-23 37 views
0

使用Google的google-auth-library Node Module時,我的刷新令牌無法正確重播請求。google-auth-library:刷新令牌無法重播請求

我收到的ERR回調的消息是:

Error: Invalid Credentials 

我已經看到了解決這一問題的其他問題,但在那裏提出的解決方案並沒有解決我的問題。

詳情:

在下面的代碼中,假定的說法googleAccessToken的樣子:

{ 
    "access_token": "AN ACCESS TOKEN", 
    "refresh_token": "A REFRESH TOKEN" 
} 

我的客戶的最低版本:

exports.nextEvent = function (googleAccessToken, cb) { 
    // Load client secrets from a local file. 
    fs.readFile('client_secret.json', function processClientSecrets(err, clientSecretContent) { 
     if (err) { 
      console.error('Error loading client secret file: ' + err); 
      return; 
     } 
     authorize(JSON.parse(clientSecretContent), getNextEvent); 
    }); 

    /** 
    * Create an OAuth2 client with the given credentials, and then execute the 
    * given callback function. 
    * 
    * @param {Object} credentials The authorization client credentials. 
    * @param {function} callback The callback to call with the authorized client. 
    */ 
    function authorize(clientCredentials, callback) { 
     var clientSecret = clientCredentials.web.client_secret; 
     var clientId = clientCredentials.web.client_id; 
     var redirectUrl = clientCredentials.web.redirect_uris[0]; 
     var auth = new googleAuth(); 
     var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); 

     oauth2Client.setCredentials(googleAccessToken); 
     callback(oauth2Client); 
    } 

    /** 
    * 
    * 
    * @param {google.auth.OAuth2} auth An authorized OAuth2 client. 
    */ 
    function getNextEvent(auth) { 
     var calendar = google.calendar('v3'); 
     calendar.events.list({ 
      auth: auth, 
      calendarId: 'primary', 
      timeMin: (new Date()).toISOString(), 
      maxResults: 10, 
      singleEvents: true, 
      orderBy: 'startTime' 
      }, 
      function (err, response) { 
       if(err){ 
        console.error(err) 
       } 
       console.log("your next events are : " + response); 
      } 
     ); 
    } 
}; 

回答

1

不知道這是你確切的用例,但我使用passport-google-oauth2來獲得初始訪問和刷新標記。

然後,我使用googleapis作爲API請求。

oauth2Client.setCredentials({ 
    access_token: 'ACCESS TOKEN HERE', 
    refresh_token: 'REFRESH TOKEN HERE' 
}); 
plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) { 
    // handle err and response 
}); 

說明文檔中提到,當訪問令牌已過期,oauth2Client會自動使用刷新令牌更新它,然後重播請求。

那麼,那部分沒有爲我工作,我總是得到Invalid Credentials

嘗試將expiry_date設置爲過去一小時以上的unix時間戳。

oauth2Client.setCredentials({ 
    access_token: 'ACCESS TOKEN HERE', 
    refresh_token: 'REFRESH TOKEN HERE' 
    expiry_date: '1469787756005' // unix timestamp more than an hour in the past (access tokens expire after an hour) 
}); 
plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) { 
    // handle err and response 
}); 

這對我有效!

+0

確實!這正是我處理它的原因:) –