【问题标题】:How to handle Google API access_token expired without using google-api-nodejs-client?如何在不使用 google-api-nodejs-client 的情况下处理 Google API access_token 过期?
【发布时间】:2018-05-31 22:35:05
【问题描述】:

我已经实现了获取 access_token、refresh_token 和 expire_date 的代码。 所有这些值都已存储在数据库中。

现在我需要一种方法来获取另一个 access_token,以防旧的过期而不使用 google-api-nodejs-client 包

原因是这个模块最近有bug,你可以在这里查看(我的评论是最新的) https://github.com/google/google-api-nodejs-client/issues/869#issuecomment-352401977 https://github.com/google/google-api-nodejs-client/issues/894.

目前,我尝试了类似的方法

GoogleTokens.findOne({isObsolete: false}).then((token) => {
                let subscriptionsGetUrl = "https://www.googleapis.com/androidpublisher/v2/applications/" + req.query.packageName + "/purchases/subscriptions/" + req.query.subscriptionId + "/tokens/" + req.query.token + "?access_token=" + token.accessToken;

                request(subscriptionsGetUrl, function (error, response, body) {
                    if (error) {
                        throw error;
                    }

                    res.success(JSON.parse(body).expiryTimeMillis);
                });
            });

但是access_token过期就会失效。

谢谢。

【问题讨论】:

  • 您需要不使用 google-api-nodejs-client 来检索新的访问令牌。如果您有刷新令牌,则可以通过 POST 请求使用刷新令牌检索新的访问令牌。你需要这样的方法。我的理解正确吗?
  • @Tanaike:嗨,我的意思是我需要检测access_token何时过期,届时我可以使用refresh_token请求一个新的。问题是,在官方文档中,我找不到如何检测access_token是否过期。
  • 感谢您的回复。我发布了一个答案。请确认。

标签: node.js google-api google-api-nodejs-client


【解决方案1】:

这个答案怎么样?您可以使用 OAuth2 API 检索访问令牌的到期时间。当你想在没有 google-api-nodejs-client 的情况下检索它时,可以使用以下方法。

示例脚本:

var uri = "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=" + accesstoken;
request.get({uri: uri}, (err, res, body) => {
    console.log(body)
});

回应:

如果访问令牌还可以使用,则返回以下响应。

{
    "azp": "#####",
    "aud": "#####",
    "sub": "#####",
    "scope": "#####",
    "exp": "1234567890", // Expiration time
    "expires_in": "3600", // Remaining time
    "access_type": "offline"
}

如果访问令牌已经无法使用,则返回如下响应。

{
 "error_description": "Invalid Value"
}

参考:

我从以下文档中得到了上述方法。

如果这对你没有用,我很抱歉。

【讨论】:

  • 谢谢田池。经过一番研究,我使用了这种方式:每当出现 401 Unauthorized 时,我都会抓住它,在 catch 中,使用 refresh_token 请求新的 access_token,并使用 access_token 再次调用 API
  • @Hoang Trinh 感谢您提供更多信息。
  • @Tanaike 刷新idToken 怎么样?详情请看here
猜你喜欢
  • 2015-06-24
  • 2013-10-23
  • 2013-12-27
  • 1970-01-01
  • 2013-09-23
  • 2011-03-15
  • 1970-01-01
  • 2021-10-11
  • 2012-06-10
相关资源
最近更新 更多