9

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?

derefed
  • 679
  • 5
  • 17

2 Answers2

8

const accessToken=oAuth2Client.getAccessToken()

This worked for me

Joe Kurian
  • 136
  • 3
  • 5
4

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',
            },
        })
  • Is that the same as what one would get from `credentials.access_token`? Is there documentation for this? – derefed Nov 19 '18 at 05:40
  • Access token does not have the 'bearer ' string so it cannot be directly used in request headers. No doc but It was explained in release not: https://github.com/googleapis/google-auth-library-nodejs/releases/tag/v2.0.0 – Arnaud JEZEQUEL Nov 21 '18 at 09:57
  • 2
    Excellent -- the documentation that you linked to mentions that you should use `getAccessToken()` instead, which is exactly what is needed (as opposed to the recommendation that the deprecation warning in my original post gives). Could you add `getAccessToken()` to the answer? Then I can accept it as the solution. – derefed Dec 03 '18 at 23:40
  • Yes, an access token can be used in HTTP headers. You build the header: header = 'authorization: Bearer ' + credentials.access_token – John Hanley Dec 27 '18 at 22:02
  • Using @derefed suggestion, I am calling `getAccessToken` and it works great for me. Wish these things were documented. – jakewies Jan 16 '19 at 14:10