Search code examples
javascriptmeteoraccess-tokenmeteor-accountsgoogle-api-js-client

Authorized client-side JS API calls with Google's gapi library with an existing access token?


Some background

I'm using Meteor as an application framework, and I use the accounts-google package to authenticate users. Using the accounts packages is very nice, because it handles all the dirty work of obtaining access tokens, refreshing them on expiry, etc. However, I wanted more profile information about the user than what gets populated in the Meteor.user() object.

With Facebook, I was able to easily load their client-side JS library and make graph api requests using Meteor.user().services.facebook.accessToken and following the documentation on the API:

https://developers.facebook.com/docs/javascript/reference/FB.api

My Problem

When referencing Google's JavaScript API, the documentation states that when making API calls, the request includes the access token automatically, but only when using gapi to handle the authorization requests.

https://developers.google.com/api-client-library/javascript/features/authentication#MakingtheAPIrequest

This is not helpful when relying on a 3rd party authorization package (or when your application handles Google's authentication away from the client side).

Is there any way to use an existing access token in requests using the gapi.client library methods?


Solution

  • I struggled over this for a long time, and I was able to find a similar question posted here:

    Google OAuth2 - Using externally generated Access Token - With JS Client Library

    However, this person already knew what had to be done, just not how to make the appropriate call, so it was fairly lucky that I found it.

    Solution

    In order to make gapi requests using an existing access token, you must call:

        gapi.auth.setToken({
            access_token: "token_string"
        });
    

    before making a client request. In Meteor, you can use Meteor.user().services.google.accessToken in place of the "token_string" above.

    Documentation on the method is here:

    https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthsetToken