Flutter Google Sign In idToken expired

Viewed 1869

I am using google_sign_in for auth in my flutter application.

I followed steps documented here to get started:

https://github.com/flutter/plugins/blob/master/packages/google_sign_in/google_sign_in/example/lib/main.dart

I get idToken as recommended to perform auth on the server side.

This is the code snippet I use to get idToken

_googleSignIn.onCurrentUserChanged.listen(
            (GoogleSignInAccount account) {
      setState(() {
        developer.log("************Changing account");
        _currentUser = account;
        account.authentication.then((key){
          developer.log("########### Changing token");
          _userToken=key.idToken;
        });

      });
    });

When I send idToken (_userToken in above example) it works fine for sometime, and later I see the following error message on the server side:

Token expired, 1593370077 < 1593384191

IT looks like token has an expiration time and expires after a while.

I tried moving above code snippet from initState() to build(). Here my assumption if I call it everytime when I am building the widget I should get a new token. THAT DIDN'T WORK

Reason I thought it might work was because when I "Run .dart" (not hot reload) it works. This made me assume moving it to build might work . It didn't work

My question: What is the programmatic way to refresh token, or get a new token in flutter using google_sign_in.

Thanks for your help!!

1 Answers

The idToken expires every 30 minutes. To refresh the token you can either user the API or do a silent login like this:

Future<String> refreshToken() async {
    final GoogleSignInAccount googleSignInAccount =
        await googleSignIn.signInSilently();
    final GoogleSignInAuthentication googleSignInAuthentication =
        await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );
    await auth.signInWithCredential(credential);

    return googleSignInAuthentication.accessToken; //new token
  }
Related