quantm
quantm

Reputation: 244

How to check GoogleCredential if it is expired

I have initialized the GoogleCredential variable from saved-access-token and saved-refresh-token. But i don't know to check it expired or not ?

I know that GoogleCredential has a function getExpiresInSeconds. But if i initialize GoogleCredential from the saved-access-token and saved-refresh-token,the function getExpiresInSeconds will return null.

This case getExpiresInSeconds will not null

mResponse = mFlow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
mCredential =  new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET).setJsonFactory(mJsonFactory).setTransport(mHttpTransport).build();
mCredential.setFromTokenResponse(mResponse);
mCredential.getExpiresInSeconds() // will return expired value in second

but in this case

String accessTokenSave = mPrefs.getString(GOOGLE_DRIVE_TOKEN, "NO KEY");
String accessRefreshTokenSave = mPrefs.getString(GOOGLE_DRIVE_REFRESH_TOKEN, "NO KEY");

mHttpTransport = new NetHttpTransport();
mJsonFactory = new JacksonFactory();
mCredential = new GoogleCredential.Builder()
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(mJsonFactory)
.setTransport(mHttpTransport).build();

mCredential.setAccessToken(accessTokenSave);
mCredential.setRefreshToken(accessRefreshTokenSave);
mCredential.getExpiresInSeconds() // will return null value

So how can i check mCredential the case load it from accessTokenSave and accessRefreshTokenSave

Upvotes: 1

Views: 4769

Answers (1)

Claudio Cherubino
Claudio Cherubino

Reputation: 15024

An access token expires in one hour while the refresh token will be valid until revoked by the user. However, you should never rely on these times and instead be prepared to catch an exception whenever credentials are no longer valid, and react accordingly.

Check the documentation for the description on the complete flow, together with sample code implementing it: https://developers.google.com/drive/credentials

Upvotes: 2

Related Questions