4

I am working on Nodejs Google Api client Oauth process. I follow what the code example for oauth, https://github.com/google/google-api-nodejs-client/blob/master/examples/oauth2.js.

I have one question. How do I check if the access token is expired and how do I use the refresh token to get another access token again?

To be more specific, let's say get access to google+ user profile, so I use the access token to get user profile:

getAccessToken(oauth2Client, function() {
    // retrieve user profile
    getUserProfile(client, oauth2Client, 'me', function(err, profile) {
      if (err) {
        console.log('An error occured', err);
        return;
      }
      console.log(profile.displayName, ':', profile.tagline);
    });
  });

In addition, in the client side of the application(backbonejs), if I am attempting to use google api JS client to access the google drive api (not google plus), I am not sure if I can use the access token I get from server side of the application (nodejs) or I have to do another OAuth using google api JS client.

4

1 回答 1

6

确定访问令牌是否过期的最佳做法是尝试使用它。尽管返回的包包含 *expires_in* 参数,表示访问令牌过期前的秒数,但这并不可靠,因为它可能随时因其他原因被撤销和替换。

然后程序通常是

  1. 尝试使用访问令牌进行呼叫
  2. 如果您收到“未授权”响应,请使用 referesh 令牌获取新的访问令牌。如果失败,您的权限已被撤销
  3. 尝试再次使用新的访问令牌进行呼叫

如果您使用该库进行其他 Google API 调用 - 这将自动为您处理。

于 2014-04-02T11:49:53.667 回答