Java: Oauth 2.0 How can I use Google API RefreshTokens to avoid requesting access every time my app launches?

StackOverflow https://stackoverflow.com/questions/8800466

Question

There is a lot of sample code for the google API showing how to Get an authorization token and use it, but I cannot find any sample code that shows you how to use the Oauth 2.0 GoogleAccessProtectedResource.refreshToken() method in the java client to get a new authorization token in in Java. Google search turns up nothing, and I can only find a C# example on Stackoverflow. If you could point me to a bit of sample code in Java showing how this is done that would be great. The platform I am working on in Android. An example of the model of OAuth 2.0 I would like to use is here: http://blog.doityourselfandroid.com/2011/08/06/oauth-2-0-flow-android/

Thanks a lot

Was it helpful?

Solution

Answering my own question here. It turned out to be quite straight forward, by calling GoogleAccessProtectedResource.refreshToken() the accesstoken is refreshed inside the class, it can be read and reused as needed through its getter.

OTHER TIPS

You would have to catch 401(unauthorized) errors. After this do something like this.

accountManager.invalidateAuthToken(accessProtectedResource.getAccessToken());
accessProtectedResource.setAccessToken(null);

After this simply get back the token. This time user will not have to authorize access again.

        accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true,
        new AccountManagerCallback<Bundle>() {
          @Override
          public void run(AccountManagerFuture<Bundle> future) {
            try {
              Bundle bundle = future.getResult();
              if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, REQUEST_AUTHENTICATE);
              } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                accessProtectedResource.setAccessToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                onAuthToken();
              }
            } catch (Exception e) {
              handleException(e);
            }
          }
        }, null);

Refer the task sample for reference and the corresponding article.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top