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

google-auth-library: Refresh token not replaying request

在使用 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);
            }
        );
    }
};

不确定这是否是您的确切用例,但我正在使用 passport-google-oauth2 获取初始访问和刷新令牌。

然后,我对 API 个请求使用 googleapis

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

这对我有用!