oauth-2.0google-oauthblockingplayngoogle-oauth-java-client

Googles AuthorizationCodeInstalledApp.authorize() method freezing on canceled auth


I have a Java application that needs to get users to authorize my application's access to Google services. I have the following bit of code in place to show and obtain the authorization I need:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JsonFactory, clientSecrets, scopes).build();
Credential cred = null; 
try
  {
    LocalServerReceiver localSrv = new LocalServerReceiver();

    AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flow, localSrv);

    cred = app.authorize(userName);
  }
  catch(Exception ex)
  {
    ex.printStackTrace();
  }
    refreshToken = cred.getRefreshToken();

If the user clicks on the 'Authorize' or 'Cancel' buttons everything's fine. If they close the browser window however, the entire application freezes. Is there a way to handle this case to prevent the freezing or introduce a timeout?


Solution

  • We're also integrating Google Drive into our application, and this is a concern of mine. What happens is that if you call the authorize() method, whatever thread the call is on will block. You'll notice that while the authorization window is open, the application also isn't responsive.

    I was hoping that there would be a way to detect if the user closed the authorization window, but it seems like this will only cause the LocalServerReceiver to wait endlessly for a token that will never arrive.

    Your best bet at this point is to call authorize() asynchronously, and to wait for a response.

    Edit: I took a peek at the LocalServerReceiver source code because we wanted the receiver to redirect to a different URL rather than display plain text. It implements the VerificationCodeReceiver interface, which has a blocking waitForCode() method. It seems like it's necessary for AuthorizationCodeInstalledApp.authorize() to block while waiting, even if you make your own implementation of VerificationCodeReceiver.