Refresh Access Token with OAuth 2.0 Google App Engine

The link you give in your question implements Google OAuth 2.0 authorization by using Google APIs Client Library for Java. And this library has implemented function of refresh access token .

So what you need is using Class GoogleRefreshTokenRequest in this library.

This class is Google-specific implementation of the OAuth 2.0 request to refresh an access token using a refresh token as specified in Refreshing an Access Token.

And its java doc also gives a sample usage:

static void refreshAccessToken() throws IOException {
try {
  TokenResponse response =
      new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
          "tGzv3JOkF0XG5Qx2TlKWIA", "s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw").execute();
  System.out.println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
  if (e.getDetails() != null) {
    System.err.println("Error: " + e.getDetails().getError());
    if (e.getDetails().getErrorDescription() != null) {
      System.err.println(e.getDetails().getErrorDescription());
    }
    if (e.getDetails().getErrorUri() != null) {
      System.err.println(e.getDetails().getErrorUri());
    }
  } else {
    System.err.println(e.getMessage());
  }
}

}

And This is another usage you can refer to.

You can add code below in CredentialManager.java, and when you need to refresh token, call this method.

public Credential refreshAccessToken(String refreshToken, String clientId, String clientSecret) throws IOException {
try {
  TokenResponse response =
  new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
      refreshToken, clientId, clientSecret).execute();
  System.out.println("Access token: " + response.getAccessToken());
  return buildEmpty().setAccessToken(response.getAccessToken());
} catch (TokenResponseException e) {
  if (e.getDetails() != null) {
    System.err.println("Error: " + e.getDetails().getError());
    if (e.getDetails().getErrorDescription() != null) {
      System.err.println(e.getDetails().getErrorDescription());
    }
    if (e.getDetails().getErrorUri() != null) {
      System.err.println(e.getDetails().getErrorUri());
    }
  } else {
    System.err.println(e.getMessage());
  }
}

another method is use DataStoreCredentialRefreshListener

Access protected resources using the GoogleCredential. Expired access tokens will automatically be refreshed using the refresh token (if applicable). Make sure to use DataStoreCredentialRefreshListener and set it for the credential using GoogleCredential.Builder.addRefreshListener(CredentialRefreshListener).


final GoogleCredential credential = new Builder()
        .setTransport(new NetHttpTransport())
        .setJsonFactory(new JacksonFactory())
        .setClientSecrets(OAuth2Provider.GOOGLE_CLIENT_ID, OAuth2Provider.GOOGLE_CLIENT_SECRET)
        .build()
        .setRefreshToken(refreshToken);

credential.refreshToken(); // do not forget to call

String newAccessToken = credential.getAccessToken();

Then you can use an object like UserTokens:

public class UserTokens {

    public final String accessToken;
    public final String refreshToken;

    public UserTokens(String accessToken, String refreshToken) {
        this.accessToken = accessToken;
        this.refreshToken = refreshToken;
    }

}

... and then store it in DB like:

TokenRepository tokenRepository = new PersistentTokenRepository();
tokenRepository.store(userTokens);

Notes

  • OAuth2Provider is my custom class where I keep client's id and secret
  • TokenRepository is a custom interface that has methods like store() and get()
  • PersistentTokenRepository is custom the implementation of the upper interface where you can store tokens in SQL or NoSQL databases like GAE