'How do I refresh identity token before it gets expired using flutter google_sign_in plugin for android

I am integrating Google Sign In Auth with my App using google_sign_in flutter plugin. It is working all fine except the idToken expires after an hour. Just before it gets expired, I am calling signInSilently to refresh the token. It works fine for iOS but for Android it returns the same old token. I looked into the code of the plugin and based on the comment on the code, it looks like by design, it doesn't refresh the token for Android.

Future<GoogleSignInAuthentication> get authentication async {
    if (_googleSignIn.currentUser != this) {
      throw StateError('User is no longer signed in.');
    }

    final GoogleSignInTokenData response =
        await GoogleSignInPlatform.instance.getTokens(
      email: email,
      shouldRecoverAuth: true,
    );

    // On Android, there isn't an API for refreshing the idToken, so re-use
    // the one we obtained on login.
    if (response.idToken == null) {
      response.idToken = _idToken;
    }
    return GoogleSignInAuthentication._(response);
  }

My question is if this is the case, how do I refresh the token (especially for the android). On the plugin repo, I have also found other developers complaining about the same issue but there is no response there.

Overall, my goal is for user do not need to sign in every time they open the apps even after a month. Thanks



Solution 1:[1]

Try this below code, I can able to open the application without signing every time its works perfectly,

const _scopes = const [cal.CalendarApi.CalendarScope];
//I'm using google sign in for the purpose of the calendar so I'm using 
//this scope

final _googleSignIn = new GoogleSignIn(scopes: _scopes);
try {
await _googleSignIn.isSignedIn().then((value) async {
  print("silently");
  await _googleSignIn.signInSilently();
});
} catch (e) {
await _googleSignIn.signIn();
}
final Map<String, dynamic> authHeaders =
  await _googleSignIn.currentUser.authHeaders;
//you can now use this new token for your purpose
_googleSignIn.currentUser.authentication.then((value) => value.idToken);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gejaa