fluttergoogle-signingoogle-fit

Obtain a new token by refresh token with google_sign_in Flutter


I'm writing an application that call google fit rest api from Flutter.

I need to sign with google using (https://pub.dev/packages/google_sign_in). I can obtain a token without problem (see Did anyone manage to get the id token from google sign in (Flutter)) but how to obtain a new token when it is expired?

I dont' want to ask to the user to login and obtain a new token every hour


Solution

  • You can do this in 2 ways.

    1. You can use the API.

    2. I don't know if this is standard but you can do a silent login every time the user opens the app, the silent log logs into the user account without user interaction and this way you have a new token. Like this:

    import 'package:google_sign_in/google_sign_in.dart';
     // you may only login with google, delete hide part if not
    import 'package:firebase_auth/firebase_auth.dart' hide EmailAuthProvider; 
    
    //...
    
    Future<void> silentSignIn() async {
        try {
          final GoogleSignIn googleSignIn = GoogleSignIn();
          final GoogleSignInAccount? googleUser =
              await googleSignIn.signInSilently();  // silent login
          if (googleUser != null) {
            final GoogleSignInAuthentication googleAuth =
                await googleUser.authentication;
            final AuthCredential credential = GoogleAuthProvider.credential(
              accessToken: googleAuth.accessToken,
              idToken: googleAuth.idToken,
            );
            await FirebaseAuth.instance.signInWithCredential(credential);
            print('User silently signed in with Google.');
          } else {
            print('No user signed in silently.');
            // Optionally, redirect to a sign-in page
          }
        } catch (e) {
          print('Error during silent sign-in: $e');
          // Handle errors or redirect to a manual sign-in page
        }
      }