简体   繁体   中英

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

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:

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

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

    return googleSignInAuthentication.accessToken; // New refreshed token
  }

Get refresh token manually

apiKey - your api key from firebase, idToken - unexpired id token, provider - 'google.com', 'apple.com' etc

final url = Uri.parse('https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=$apiKey');

final response = await http.post(
  url,
  headers: {'Content-type': 'application/json'},
  body: jsonEncode({
    'postBody': 'id_token=$token&providerId=$provider',
    'requestUri': 'http://localhost',
    'returnIdpCredential': true,
    'returnSecureToken': true
  })
);
if (response.statusCode != 200) {
  throw 'Refresh token request failed: ${response.statusCode}';
}

final data = Map<String, dynamic>.of(jsonDecode(response.body));
if (data.containsKey('refreshToken')) {
   // here is your refresh token, store it in a secure way
} else {
  throw 'No refresh token in response';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM