如何使用 flutter 在后台 google-apis 中正确刷新身份验证令牌

How to correctly refresh auth token in the background google-apis using flutter

现在我使用方法 clientViaUserConsent 来验证我的用户,因此能够使用 Google API,在在这种情况下,calendar api,问题在于它的构建方式现在每次用户进入应用程序时都会请求此权限,这是一个问题,因为它很烦人对于用户,

有没有办法在每次用户进入应用时在后台刷新身份验证令牌来自动执行此操作?

存储token和刷新token的思路我明白了,但是不知道怎么实现

这是我的代码:

var _clientID = new ClientId(Secret.getId(), "");
    const _scopes = const [cal.CalendarApi.calendarScope];
    await clientViaUserConsent(_clientID, _scopes, Prompt.prompt).then((AuthClient client) async {
      CalendarClient.calendar = cal.CalendarApi(client);
      print(client);
    });

是的,凭据存储在客户端变量中。

AccessToken: client.credentials.accessToken.data
RefreshToken: client.credentials.refreshToken
Expiration: client.credentials.accessToken.expiry
IDToken: client.credentials.idToken

然后您可以存储这些并在以后他们这样登录时构建一个新请求:

void getEventsPastAuth() async {
  var client = Client();
  AccessCredentials credentials = await _calendarCredentials.getCredetial();
  AccessCredentials refreshedCred =
      await refreshCredentials(_credentialsID, credentials, client);

  client = autoRefreshingClient(_credentialsID, credentials, client);
  var calendar = CalendarApi(client);
  var now = DateTime.now();
  var calEvents = calendar.events.list('primary',
      maxResults: 100,
      timeMin: now,
      timeMax: DateTime(now.year, now.month + 1, now.day));
  calEvents.then((Events events) {
    events.items!.forEach((Event event) {
      debugPrint(event.summary);
    });
  });
}

变量 credentials 是作为 AccessCredential 存储的变量

AccessCredentials(
      AccessToken("Bearer", accessToken, DateTime.parse(expiration)),
      refreshToken,
      _scopes,
      idToken: idToken);

如果您知道如何同时访问多个用户的日历,请告诉我。我目前正在努力弄清楚如何在 Flutter 中获得用户同意后搜索多个用户的日历。