我有一个 Java 应用程序需要让用户授权我的应用程序访问 Google 服务。我有以下代码来显示和获得我需要的授权:
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();
如果用户点击“授权”或“取消”按钮,一切正常。但是,如果他们关闭浏览器窗口,整个应用程序就会卡住。有没有办法处理这种情况以防止卡住或引入超时?
最佳答案
我们还将 Google 云端硬盘集成到我们的应用程序中,这是我的一个顾虑。发生的情况是,如果您调用 authorize()
方法,调用的任何线程都将阻塞。您会注意到,虽然授权窗口打开,但应用程序也没有响应。
我希望有一种方法可以检测用户是否关闭了授权窗口,但似乎这只会导致 LocalServerReceiver
无休止地等待永远不会到达的 token 。
此时您最好的选择是异步调用authorize()
,然后等待响应。
编辑:我看了一下 LocalServerReceiver
源代码,因为我们希望接收器重定向到不同的 URL 而不是显示纯文本。它实现了 VerificationCodeReceiver
接口(interface),该接口(interface)具有阻塞式 waitForCode()
方法。似乎 AuthorizationCodeInstalledApp.authorize()
在等待时阻塞是必要的,即使您自己实现了 VerificationCodeReceiver
。
关于oauth-2.0 - Googles AuthorizationCodeInstalledApp.authorize() 方法在取消身份验证时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23857976/