I'm using Google One-Tap sign in to authenticate users, and after the user is authenticated I get an access token. I know that I can use this access token in order to work with the Google API client for JavaScript ("GAPI"). But I can't find any way to work with GAPI using this access token.
Is there any way to use GAPI assuming I already have an logged in user?
What I'm trying to do is access the user calendar after simply authenticating with One-Tap authentication and giving consent for the calendar once.
First of all:
There is no way to "authenticate" the google JS api client with the response that is returned by the One-Tap sign in.
Luckily we don't need to authenticate with the gapi JS client because we use a handy function called
gapi.auth2.authorize
!How to autorize the gapi client
It's important to first read the docs and understand their warning:
Now the question is how to completely avoid the init/signIn method.
Step 1
Sign the user into the Google One-Tap sign in.
Step 2
Load the gapi client:
window.gapi.load('client')
Step 3
Pass the
credential.id
(the email address) returned by Google One-Tap as thelogin_hint
param in the call to authorize. This will preselect the account and we can try to not show any new login pop-up (promt).Example:
Using prompt: 'none', you can try to fetch a token without any UI. This is useful to check whether you need to show an Authorize button, and also useful before making any call to the Calendar API to get a fresh token.
Step 4
Before we can make any call to
gapi.client.calendar
we need to initialize theclient
with just the calendardiscoveryDocs
.This is the most tricky part and is not properly documented anywhere! The only thing we can retrieve from the
api.client.init()
documentation is the following line:This basically means: as soon as you give either
clientID
orscope
gapi.client.init
will try and start the traditional authentication method.In our case: we don't need to pass the
clientID
orscope
as we've already done this in step 3.So how does the client know which module to initialize? → By only passing the discoveryDocs of the module you want to use! In this case the calendar discoveryDocs.
Step 5
Now you're done! You can make requests with e.g.
gapi.client.calendar.events.list()
Full example
A full code example can be found here below: