Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use Google API getRequestHeaders() to get an OAuth2 access token?

I'm using the googleapis npm library to authorize using OAuth2 to access my Gmail account to send emails. I am using the following code (TypeScript) to do that:

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 || '';

This code works, but I get the following message:

(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.

I have searched on Google, on the GitHub for the googleapis module, on StackOverflow, and I haven't been able to find any documentation for what constitutes the getRequestHeaders method. I've tried calling getRequestHeaders, but it doesn't appear to return a credentials object with an access token.

Are there official docs for how getRequestHeaders should be used in this situation?

like image 343
derefed Avatar asked Nov 01 '18 03:11

derefed


People also ask

How do I get access token for Google REST API?

Obtain an access token manually You will need to create a JSON Web Token (JWT) and sign it with the private key, then construct an access token request in the appropriate format. After that, your application sends the token request to the Google OAuth 2.0 Authorization Server and an access token gets returned.


2 Answers

const accessToken=oAuth2Client.getAccessToken()

This worked for me

like image 194
Joe Kurian Avatar answered Oct 21 '22 16:10

Joe Kurian


This new function directly gives you an 'Headers' object:

{ Authorization: 'Bearer xxxxxxxxx' }

So you can happend it directly use it as your header object:

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

Or extract the Authorization part:

const authHeaders = await this.auth.getRequestHeaders();
yourfetchlibrary.get('https://......', {
            headers: {
                'Authorization': authHeaders.Authorization,
                'Content-Type': 'application/json',
            },
        })
like image 25
Arnaud JEZEQUEL Avatar answered Oct 21 '22 15:10

Arnaud JEZEQUEL