Java – how to get offline tokens and refresh tokens and automatically refresh access to Google APIs

I am developing an application that uses oauth2 and Google client library (located in appengine and GWT btw) to access Google API (starting from calendar API)

I implemented my oauth2call fallback servlet and extended Google abstractappengine authorizationcodecallbackservlet

I have a job, I can visit, I can view the calendar, etc., but there are two problems:

1) I didn't get a refresh token, although I explicitly requested 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 can't see how to set the auto refresh function These pages describe these methods:

> Class Credential. Builder > Class CredentialStoreRefreshListener

But I can't see where to add a refresh listener With credential Different from the builder class, Google authorizationcodeflow There is no such method in the builder class

After editing the debugging code, when the certificate comes back (in the onsuccess () method), it seems that a refreshlistener setting has been So maybe this is the default. My only problem is that I don't get refresh_ Token, although it is required

You may also need to view the settings in the Google API console?

Solution

One thing you should note is that a refresh token (other than an access token) is returned only if the user explicitly agrees to the requested scope Basically, when the approval page is displayed All subsequent processes will only return access tokens

Now, to test your application and ensure that you receive a refresh token for the first time, you can use approval_ Prompt = force parameter (builder. Setapprovalprompt ("force")) to ensure that the approval page is displayed in the process, and you have the explicit consent of the user After resolving any problems, make sure that the refresh token is stored correctly, and you can delete the flag (automatic by default)

More information can also be found in the developer's Guide of the offline access section

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>