Reputation: 1257
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
Upvotes: 18
Views: 8252
Reputation: 7660
You can do this in 2 ways.
You can use the API.
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:
import 'package:google_sign_in/google_sign_in.dart';
// you may only login with google, delete hide part if not
import 'package:firebase_auth/firebase_auth.dart' hide EmailAuthProvider;
//...
Future<void> silentSignIn() async {
try {
final GoogleSignIn googleSignIn = GoogleSignIn();
final GoogleSignInAccount? googleUser =
await googleSignIn.signInSilently(); // silent login
if (googleUser != null) {
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
print('User silently signed in with Google.');
} else {
print('No user signed in silently.');
// Optionally, redirect to a sign-in page
}
} catch (e) {
print('Error during silent sign-in: $e');
// Handle errors or redirect to a manual sign-in page
}
}
Upvotes: 11
Reputation: 45
Before calling '.signIn()' method make sure that GoogleSignInAccount variable type has 'forceCodeForRefreshToken' set up with true.
After that take 'serverAuthCode' and make a request to https://accounts.google.com/o/oauth2/token with the next body
'access_type': 'offline', tokenType: <serverAuthCode>, 'grant_type': 'code', 'client_secret': <yourClientSecret>, 'client_id': <yourClientId>, 'redirect_uri': <yourMiddleWare>,
.
In response you will get that refresh_token.
Upvotes: 0