In the Google documentation for OAuth2, building a GoogleCredential with an auth token is described here:
Credential and Credential Store
In particular this code snippet is offered:
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
Plus plus = Plus.builder(new NetHttpTransport(), new JacksonFactory())
.setApplicationName("Google-PlusSample/1.0")
.setHttpRequestInitializer(credential)
.build()
When I try to build a GoogleCredential in this way I am tersely informed:
Please use the Builder and call setJsonFactory, setTransport and setClientSecrets
in the message field of an exception. I downloaded the libraries for this last week so I am not sure what is happening. Is the documentation simply outdated, and if so, what method has replaced this one as best practice for building from an existing auth token and refresh token?
Incidentally, the reason using the Builder was not an option was that there WAS no client secret provided by the Google application console; it says that they are no longer provided for Android apps and the like. setClientSecrets(...), therefore, couldn't be called.
I met this problem recently and figured out the solution for my case.
Here is the running conditions: the program is running on Android 4.0 and does not use Google Drive SDK, because it could not allow our program to read the files on Google Drive which are not created by our program. I use the com.google.api.services.drive.* and com.google.api.client.googleapis.auth.oauth2.* Java libraries.
the code arose this problem is like below :
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
.setAccessType("offline")
.setApprovalPrompt("auto").build();
GoogleTokenResponse response = null;
try {
response = flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
} catch (IOException e) {
e.printStackTrace();
}
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
but above code worked well if the parameter to setAccessType("online");
and the resolution for this issue depends on what kind of accessType you want.
if you want "onLine" as the accessType, then use setFromTokenResponse()should be ok.
if you want "offline" as the accessType, then you need to use blow code :
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build()
.setFromTokenResponse(response);
One thing need to be mentioned is that you need to keep the accessType setting to be consistent for GoogleTokenResponse and GoogleAuthorizationCodeFlow creation.
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