I want to obtain a new "access token" based on the "refresh token" saved in database.
Here is the code I wrote:
GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET);
credentialBuilder.addRefreshListener(new MyCredentialRefreshListener());
credential = credentialBuilder.build();
credential.setRefreshToken("saved_refresh_token_from_database");
try {
credential.refreshToken();
} catch (IOException e) {
e.printStackTrace();
}
class MyCredentialRefreshListener implements CredentialRefreshListener {
public void onTokenResponse(Credential cr, TokenResponse tr) {
System.out.println("Credential was refreshed successfully.");
}
public void onTokenErrorResponse(Credential cr, TokenErrorResponse tr) {
System.out.println(tr);
}
}
I get this message:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad
Request { "error" : "invalid_grant" }
I use the same CLIENT_ID, CLIENT_SECRET and "refresh token" in a php script and there I managed to get the new "access token" using "refresh token" when "access token" expired.
I wrote the code based on javadoc.google-oauth-java-client.
Any person here knows how to modify the code to obtain the new access token ?
Thanks in advance.
UPDATE: the problem was that I was saving in the database the refresh_token without doing a json_decode on it and it contained a "\" which is considered escaped character in JSON.
It looks like you may have found some out of date documentation. The JavaDoc you link is for version 1.8 of the client library. The current version is 1.12.
The client library authors recommend that you use GoogleAuthorizationCodeFlow
to manage your OAuth credentials. It takes care of refreshes automatically. If you follow this path, the code will look something like this:
// Create the flow
AuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
new UrlFetchTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET,
Collections.singleton(OAUTH_SCOPES))
.setAccessType("offline")
.setCredentialStore(new AppEngineCredentialStore())
.build();
// User Id: e.g. from session
Credential credential = authorizationCodeFlow.loadCredential(USER_ID);
// Make your API call. This example uses the Google+ API
// If the access token has expired, it will automatically refresh
Plus plus = new Plus(new UrlFetchTransport(), new JacksonFactory(), credential)
.activities().list("me", "public").execute();
if you get http status 400, and message "invalid_grant". I think you should check your instance of HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET.
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