如何使用Google API getRequestHeaders()获取OAuth2访问令牌?

问题描述 投票:4回答:2

我正在使用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
2个回答
2
投票

const accessToken=oAuth2Client.getAccessToken()

这对我有用


3
投票

这个新函数直接为您提供了一个'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',
            },
        })
© www.soinside.com 2019 - 2024. All rights reserved.