I've successfully integrated GoogleSignIn into my Android app, but after 1 hour, the access token expires. How do I refresh the token?
I've checked out the entire docs for GoogleSignIn but there's nothing on refreshing the accessToken
https://developers.google.com/identity/sign-in/android/start-integrating
I've also tried searching for a method that has something like ".refreshAccessToken()"

How do I refresh the token? Why is there nothing about it in the docs?
The approach below works if you have control of the server powering your Android project. I'll use Java to illustrate since your screenshot is in Java.
From the attached image, I can see that you are able to retrieve GoogleSignInAccount after authenticating the user. You can get a server auth code from this by performing:
String authCode = account.getServerAuthCode();
You can then send this auth code to your server and exchange it for a refresh token using the GoogleAuthorizationCodeTokenRequest class. Here's an illustration below:
String CLIENT_SECRET_FILE = "/path/to/client_secret.json";
String REDIRECT_URI = "" //Leave empty if you don't have a redirect url
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v4/token", clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode, REDIRECT_URI).execute();
String accessToken = tokenResponse.getAccessToken();
String refreshToken = tokenResponse.getRefreshToken();
Long expiresInSeconds = tokenResponse.getExpiresInSeconds();
Lastly, you can plug the refresh token to your GoogleCredential like below:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setClientSecrets(clientSecrets)
.build();
credential.setAccessToken(accessToken);
credential.setExpiresInSeconds(expiresInSeconds);
credential.setRefreshToken(refreshToken);
That's it. You can get more information about this process here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With