iart
iart

Reputation: 288

GoogleCredentialsBuilder OAuth 2.0

We currently have a batch job that refreshes the access token using the refresh token every 50 minutes or so.

This is how we currently construct the GoogleCredentials object to construct the gmail api.

            Credential cred = new GoogleCredential.Builder()
                        .setTransport(httpTransport)
                        .setJsonFactory(jsonFactory)
                        .setClientSecrets(clientId, clientSecret)
                        .build()
                        .setAccessToken(accessToken)
                        .setRefreshToken(refreshToken);
           return new Gmail.Builder(httpTransport, jsonFactory, cred).setApplicationName("SalesforceIQ").build();

I don't see any advantage of setting the refreshToken in the GoogleCredentials. I am able to successfully authorize myself and return correct responses with just the access token.

Is the advantage of setting the refresh token that the accessToken is refreshed by google when invalid (during an API request)? If so, is there a way of getting this new access token back from google (so that we can store it in our db)?

Upvotes: 0

Views: 226

Answers (1)

Kilian
Kilian

Reputation: 306

Have a look at the documentation page Using OAuth 2.0 with the Google API Client Library for Java - Data store

You may use DataStoreCredentialRefreshListener and set it for the credential using GoogleCredential.Builder.addRefreshListener(CredentialRefreshListener).

The refresh listener will be called when the access token is automatically refreshed by the library and the new token is stored in the data store.

That way there is no need to set the refresh token. You might even question if the batch to automatically refresh tokens is even necessary.

Upvotes: 1

Related Questions