Autorefreshing Google authentication on Flutter (iOS and Android)
davidmartos96 opened this issue · 0 comments
Hello,
I'm having some trouble figuring out what is the correct way to handle the auto refreshing of access tokens when using Flutter (iOS and Android) with the google_sign_in
package.
The function (code below) is called every 24 hours and the user has signed in with Google already. Using reAuthenticate
before using the API has resolved some tests I've done locally where the access token expires after a few hours.
However, I'm still seeing some issues on crashlytics where using the API can fail unexpectedly after it working fine before. The error I'm seeing is the following: DetailedApiRequestError(status: 401, message: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.
It doesn't seem to be a generalized error, but I'm wondering if it's because of the implementation. I found the googleapis_auth
package and all the configuration (auto-refresh, etc...) available for Console/Server applications, which is great. But I couldn't find any example for Flutter apps where the google_sign_in
package is used.
Code
Future<void> _doSomethingWithDriveAPI() async {
// "signIn" is the GoogleSignIn instance, with the necessary scopes
// ReAuthenticate is provided
final GoogleSignInAccount? _account = await signIn.signInSilently(
suppressErrors: false,
reAuthenticate: true
);
final Map<String, String> authHeaders = await _account!.authHeaders;
// This is a http.Client that adds the headers obtained from google_sign_in
final _GoogleAuthClient googleAuthClient = _GoogleAuthClient(authHeaders);
final driveAPI = DriveApi(googleAuthClient);
// Interact with driveAPI ...
}