Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh Access Token with OAuth 2.0 Google App Engine

I would like to implement the auto-refresh method to obtain a new Access Token given the Refresh Token already taken from the first authorization flow.

Which method or list of methods should I call to do that? I'm using Java and OAuth 2.0 for Web Application. Given OAuth 2.0 WebApplication, what should I add in this code to get everything to work correctly?

like image 758
Aerox Avatar asked Jun 09 '14 20:06

Aerox


2 Answers

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).

like image 188
Owen Cao Avatar answered Sep 22 '22 19:09

Owen Cao


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
like image 24
panayot_kulchev_bg Avatar answered Sep 24 '22 19:09

panayot_kulchev_bg