微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取 Google 访问令牌的问题

如何解决获取 Google 访问令牌的问题

我一直在尝试使用下面的函数从刷新令牌中获取 Google 访问令牌。我很确定初始授权工作正常,因为在遵循标准 OAuth 流程并交换令牌代码后,我按预期返回了刷新令牌和访问令牌。如果我使用该访问令牌发出请求,它就可以工作。但是,如果我存储刷新令牌并使用下面的代码获取最新的访问令牌,我会收到消息:

{
   "error": {
      "code": 401,"message": "Request had invalid authentication credentials. Expected OAuth 2 access token,login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","status": "UNAUTHENTICATED"
   }
}

这是我正在使用的函数

async function getAccesstoken(userId) {
    const credentials = JSON.parse(await decrypt('encrypted','credentials','google','oauth'));
    const tokens = JSON.parse(await decrypt('userTokens','googleMyBusinessTokens',userId,'tokens'));
    const url = 'https://oauth2.googleapis.com/token';
    const payload = {
        client_id: credentials.web.client_id,client_secret: credentials.web.client_secret,refresh_token: tokens.refresh_token,grant_type: 'refresh_token'
    }
    const { data } = await axios.post(url,payload);
    return data;
}

函数似乎返回了我想要的东西(包括在下面),但访问令牌的工作方式与我第一次连接用户或在 OAuth 操场上获得的令牌不同。

{
  access_token: 'xxxxx',expires_in: 3599,scope: 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/business.manage',token_type: 'Bearer',id_token: 'xxxxxx'
}

如果相关,我正在尝试使用上述访问令牌向 https://mybusiness.googleapis.com/v4/accounts/{account_id}/locations 发出 GET 请求。正如我所说,如果使用我在身份验证时返回的第一个访问令牌,则可以在 OAuth 游乐场和我的代码上完美运行。上面返回的范围与我在 OAuth playground 上看到的一致,所以也不要认为是这样。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。