How to refresh expired google sign-in logins?

瘦欲@ 提交于 2019-11-28 04:41:38

If the token is expired, you can call gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse(). It returns a Promise.

maxim

FWIW, we've managed to (mostly) make it work via a listener approach. It appears that 'userChanged' callback is invoked ~5 minutes before the access token expires. That's enough for us to extract and update the access token without refreshing the page.

What does not quite work though is when computer comes back from sleep. This can be solved relatively easy by reloading the page on wake up.

You can accomplish this with listeners.

var auth2 = gapi.auth2.getAuthInstance();

// Listen for changes to current user.
// (called shortly before expiration)
auth2.currentUser.listen(function(user){

    // use new user in your OpenID Connect flow

});

This will allow you to keep current credentials, as long as the browser remains active.

If the computer is put to sleep additional work must done to get current credentials.

if (auth2.isSignedIn.get() == true) {
    auth2.signIn();
}

You can use Refresh Token to get offline access. As per the official reference

Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

Basically you will get the refresh token the first time you ask for authentication. You need to save that token securely for future use. The access token (you mentioned as identity token) expires after an hour. After that you have to use the refresh token each time you want to get a new usable access token.

Depending on the client library you are using the syntax will differ. following is a sample for php client library.

// get access token from refresh token if access token expire

if($client->getAuth()->isAccessTokenExpired()) {
    $client->refreshToken($securelyPreservedRefreshToken);
    $newToken = $client->getAccessToken();
}

check this for details steps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!