google-auth-library:刷新令牌不重播请求

时间:2016-05-23 13:49:52

标签: node.js google-calendar-api google-authentication

在使用Google的google-auth-library节点模块时,我的刷新令牌无法正确重播请求。

我在错误回调中收到的消息是:

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 个答案:

答案 0 :(得分: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 
});

这对我有用!

相关问题