Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get offline token and refresh token and auto-refresh access to Google API

I'm developing an app that accesses Google APIs (starting with Calendar API) using OAuth2 and the google client libraries for that (is on Appengine and GWT BTW).

I have implemented my OAuth2Call back servlet, extending the Google AbstractAppEngineAuthorizationCodeCallbackServlet.

I have it working, I get access and can look at calendars etc, but have two problems:

1) I do not get a refresh token, despite explicitly requesting offline access:

public static GoogleAuthorizationCodeFlow newFlow( String scope ) throws IOException {
    GoogleAuthorizationCodeFlow.Builder builder = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, 
            JSON_FACTORY,
            getClientSecrets(), 
            Collections.singleton( scope ) );

    builder.setCredentialStore( new AppEngineCredentialStore() ).setAccessType("offline");

    return builder.build();
}

2) I cannot see how to set the automatic refresh functionality. These pages describe the methods:

  • Class Credential.Builder
  • Class CredentialStoreRefreshListener

But I can't see where to add the refresh listener. There is no such method in the GoogleAuthorizationCodeFlow.Builder class, unlike the Credential.Builder class

EDIT After debugging the code more, when the credential comes back (in the onSuccess() method) it seems to have a RefreshListener set already.....so maybe that's their by default, and my only problem is I'm not getting a refresh_token, despite asking for it.

Maybe need to review settings in the Google API Console also?

like image 619
Andrew Mackenzie Avatar asked Dec 08 '12 13:12

Andrew Mackenzie


1 Answers

One thing you should be careful about: a refresh token is returned (in addition to the access token) only when the user gives consent explicitly for the requested scopes. Basically, when the approval page is shown. All subsequent flows will only return an access token.

Now, in order to test your application and make sure you receive the refresh token the first time around, you could use the approval_prompt=force parameter (builder.setApprovalPrompt("force")) to make sure the approval page is shown in the flow and you obtain explicit consent from the user. After you sort out any issues and make sure the refresh tokens are stored properly, you can remove that flag (the default is auto)

More information is also available in the offline access section in the developer guide.

like image 132
vlatko Avatar answered Oct 07 '22 15:10

vlatko