quantm
quantm

Reputation: 244

How to refresh Token in GoogleCredential

I have implement function retrieve credentials from saved token in SharedPreferences.

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

mCredential.setRefreshToken(accessRefreshTokenSave);
mCredential.setAccessToken(accessTokenSave);

Long expires = mCredential.getExpiresInSeconds();
boolean result = mCredential.refreshToken();

When the token is expired. We should call mCredential.refreshToken() to refresh the token, is it right ?

When i call refreshToken i got exception.

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant"
}

What should i need to do to refresh the token ? I found some document in Using OAuth 2.0 say about refresh token. But i don't know how to implement it in Android code? Is there any sample code do this ?

Upvotes: 1

Views: 3917

Answers (2)

Aerox
Aerox

Reputation: 679

Have a look on https://developers.google.com/+/mobile/android/sign-in that's the OAUTH for Android, and you can check what is wrong, or maybe use the example code in your Project. To give you more details, you have to post the entire project (linking it to GitHub for example) or post the interested Class ;-)

Upvotes: 0

pinoyyid
pinoyyid

Reputation: 22316

Generally (in my experience, since I haven't found any documentation) 'invalid grant' means there is some problem with your stored refresh token. This includes (I think):-

  1. The user has revoked it
  2. Your testing has caused multiple refresh tokens to be generated. Only 25 may be extant
  3. The scopes associated with the stored token have changed

To recover the situation, delete the stored refresh token and start the process again. The good news, is that apart from the user revocation scenario (1) this is a testing environment issue and doesn't necessarily mean you have a bug.

Upvotes: 1

Related Questions