通过使用google_sign_in Flutter刷新令牌获取新令牌

cczfrluj  于 2023-01-14  发布在  Flutter
关注(0)|答案(2)|浏览(124)

我正在写一个应用程序,调用谷歌适合休息API从Flutter。
我需要使用(https://pub.dev/packages/google_sign_in)与谷歌签约。我可以毫无问题地获得令牌(参见Did anyone manage to get the id token from google sign in (Flutter)),但如何在令牌过期时获得新令牌?
我不想要求用户每小时登录并获取一个新令牌

kgsdhlau

kgsdhlau1#

你可以用两种方法来做到这一点。
1.您可以使用API
1.我不知道这是否是标准的,但你可以在用户每次打开应用时执行silent login,静默日志在没有用户交互的情况下登录到用户帐户,这样你就有了一个新的令牌。

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
  }
7gcisfzg

7gcisfzg2#

手动获取刷新令牌
apiKey -来自firebase的API密钥,idToken -未过期的ID令牌,提供商-“google.com”、“apple.com”等

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';
}

相关问题