简体   繁体   English

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

[英]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.我正在编写一个从 Flutter 调用 google fit rest api 的应用程序。

I need to sign with google using ( https://pub.dev/packages/google_sign_in ).我需要使用 ( 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?我可以毫无问题地获得令牌(请参阅是否有人设法从谷歌登录(Flutter)获取 ID 令牌)但是如何在过期时获取新令牌?

I dont' want to ask to the user to login and obtain a new token every hour我不想要求用户每小时登录并获取一个新令牌

You can do this in 2 ways.您可以通过 2 种方式做到这一点。

  1. You can use the API .您可以使用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.我不知道这是否是标准的,但您可以在每次用户打开应用程序时进行静默silent login ,静默日志无需用户交互即可登录用户帐户,这样您就有了一个新令牌。 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 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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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