如果浏览器关闭,GoogleWebAuthorizationBroker.AuthorizeAsync()会挂起

时间:2017-03-31 08:54:02

标签: c# google-api google-drive-api google-api-dotnet-client

我正在编写一个可以将其输出复制到用户Google云端硬盘的C#桌面应用。但是,当我尝试使用GoogleWebAuthorizationBroker.AuthorizeAsync()授权访问Google时,如果用户在浏览器中关闭了身份验证页面,则该方法永远不会返回!

即使我使用了30秒的取消令牌,如果浏览器关闭,它也永远不会返回。

public bool Authorise()
{
    _authorised = false;
    UserCredential credential = null;
    try
    {
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        CancellationTokenSource cts = new CancellationTokenSource(new TimeSpan(0,0,30));
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = this.ClientId, ClientSecret = this.ClientSecret },
                                                                 Scopes,
                                                                 UserName,
                                                                 cts.Token,//CancellationToken.None,
                                                                 new FileDataStore(AppName)).Result;
    }
    catch (Exception)
    {
        return _authorised;
    }

    if ((credential != null) && (credential.Token.AccessToken != null))
    {

        Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, });
        _authorised = true;
    }

    return _authorised;
}

如何捕获用户关闭浏览器窗口并停止我的应用程序挂起?

4 个答案:

答案 0 :(得分:2)

这是Google .net客户端库中的已知问题。

  1. GoogleWebAuthorizationBroker.AuthorizeAsync Hang when user closes browser
  2. No time out on GoogleWebAuthorizationBroker.AuthorizeAsync?
  3. 目前我还没有解决方法。我建议您在论坛上添加您的姓名,以鼓励团队解决问题。

    更新:现在列在GoogleWebAuthorizationBroker does not honour CancellationToken when waiting for browser response

    列表中

答案 1 :(得分:0)

通常,检测用户何时关闭浏览器窗口/选项卡是不可能的。 例如,如果用户已在运行其默认浏览器,则GoogleWebAuthorizationBroker会打开一个新标签,但这不会在LocalServerCodeReceiver中启动的过程中运行。新流程立即终止。

然而,目前传递给GoogleWebAuthorizationBroker.AuthorizeAsync的CancellationToken在等待auth响应时并不受尊重,这意味着即使尝试使用简单的超时也不起作用。 #968提出要解决此问题。

答案 2 :(得分:0)

您可以使用BackgroundWorker进行修复。 如果浏览器已关闭,则background_RunWorkerCompleted将被触发。

别忘了使用FileDataStore, 因为您无法从BackgroundWorker获取凭据变量。

答案 3 :(得分:0)

我能够通过将API调用添加到其他线程来解决此问题,这避免了主应用程序挂起。然后添加超时或特定条件以关闭线程

相关问题