Reputation: 3569
I'm migrating a web app that interacts with the google drive js api to the new Google Identity Services API and following this quickstart guide. GIS is mandatory, since the old one will no longer be in use from March 2023.
In this guide, there is only one small note mentionning to preserve the logged in state after page reload:
Note: After the initial user authorization, you can call gapi.auth.authorize with immediate:true to obtain an auth token without user interaction.
However, there's no clear code example how to do that, furthermore one can find in the migration guide, that gapi.auth2.authorize()
is deprecated.
requestAccessToken()
after every page reload without user interaction is not an option, because 1st the popup is not shown at all (blocked in all major browsers) and 2nd if allowed the popup is shown and hiding immediately (bad ui)Can somebody give me an example where GSI is used via JS that preserves sessions through page reloads?
It seems that Google Identity Services is not yet production ready or am I wrong?
Upvotes: 11
Views: 1561
Reputation: 260
In order to help:
Solution
As Sam described: "you can somehow save access token and use it to speed-up things after page reload."
Given the the Google's exampe, we should call initTokenClient
in order to configure the Google Auth and the requestAccessToken
to popup the auth:
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: 'YOUR_CLIENT_ID',
scope: 'https://www.googleapis.com/auth/calendar.readonly',
prompt: 'consent',
callback: tokenCallback
});
tokenClient.requestAccessToken({prompt: ''})
In your tokenCallback
you can save the credentials you get somehow, e.g.:
const tokenCallback(credentials) => {
// save here the credentials using localStorage or cookies or whatever you want to.
}
Finally, when you restart/reload your application and you initialize the gapi.server
again, you only need to get the credentials again and set token to gapi
, like:
gapi.load('client', function() {
gapi.client.init({}).then(function() {
let credentials = // get your credentials from where you saved it
credentials = JSON.parse(credentials); // parse it if you got it as string
gapi.client.setToken(credentials);
... continue you app ...
}).catch(function(err) {
// do catch...
});
});
Doing it, your application will work after the reload. I know it could not be the best solution, but seeing what you have and the library offers, I think that's you can do.
p.s.: the token expires after 1 hour and there is no refresh token (using the implicit flow) so, you will have to ask the user to sign-in again.
Upvotes: 0