【问题标题】:How do you use Google API getRequestHeaders() to get an OAuth2 access token?您如何使用 Google API getRequestHeaders() 获取 OAuth2 访问令牌?
【发布时间】:2019-04-05 06:56:48
【问题描述】:

我正在使用googleapis npm 库授权使用 OAuth2 访问我的 Gmail 帐户以发送电子邮件。我正在使用以下代码(TypeScript)来做到这一点:

const oAuth2Client = new google.auth.OAuth2(
  googleConfig.clientId,
  googleConfig.clientSecret
);

oAuth2Client.setCredentials({
  refresh_token: googleConfig.refreshToken
});

const accessTokenRetVal = (await oAuth2Client.refreshAccessToken()).credentials.access_token;
const accessToken = accessTokenRetVal || '';

此代码有效,但我收到以下消息:

(node:8676) [google-auth-library:DEP007] DeprecationWarning: The `refreshAccessToken` method has been deprecated, and will be removed in the 3.0 release of google-auth-library. Please use the `getRequestHeaders` method instead.

我在 Google、GitHub 上搜索了 googleapis 模块、在 StackOverflow 上,但我无法找到任何有关 getRequestHeaders 方法的文档。我尝试调用getRequestHeaders,但它似乎没有返回带有访问令牌的credentials 对象。

是否有官方文档说明在这种情况下应该如何使用getRequestHeaders

【问题讨论】:

    标签: google-api-nodejs-client google-auth-library


    【解决方案1】:

    const accessToken=oAuth2Client.getAccessToken()

    这对我有用

    【讨论】:

      【解决方案2】:

      这个新函数直接给你一个'Headers'对象:

      { Authorization: 'Bearer xxxxxxxxx' }
      

      所以你可以直接将它用作你的标题对象:

      const authHeaders = await this.auth.getRequestHeaders();
      yourfetchlibrary.get('https://......', {
                  headers: authHeaders,
              })
      

      或者提取授权部分:

      const authHeaders = await this.auth.getRequestHeaders();
      yourfetchlibrary.get('https://......', {
                  headers: {
                      'Authorization': authHeaders.Authorization,
                      'Content-Type': 'application/json',
                  },
              })
      

      【讨论】:

      • 这和从credentials.access_token 得到的一样吗?有这方面的文档吗?
      • 访问令牌没有 'bearer' 字符串,因此不能直接在请求标头中使用。没有文档,但在发布中没有解释:github.com/googleapis/google-auth-library-nodejs/releases/tag/…
      • 非常好——您链接到的文档提到您应该使用getAccessToken(),这正是需要的(与我原始帖子中的弃用警告给出的建议相反)。您可以在答案中添加getAccessToken() 吗?然后我可以接受它作为解决方案。
      • 是的,可以在 HTTP 标头中使用访问令牌。您构建标头: header = 'authorization: Bearer' + credentials.access_token
      • 使用@derefed 建议,我打电话给getAccessToken,它对我很有用。希望这些事情被记录在案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2013-03-25
      • 1970-01-01
      • 2022-11-28
      • 2016-07-07
      • 2021-11-10
      • 2021-10-10
      相关资源
      最近更新 更多