Reputation: 53
I'm writing a C# desktop app that can copy its output to a users Google Drive. However when I try an authorise access to Google with GoogleWebAuthorizationBroker.AuthorizeAsync() if the user closes the authentication page in the browser the method never returns!
Even if I use a 30 sec cancellation token it never returns if the browser is closed.
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;
}
How can I trap the user closing the browser window and stop my application hanging?
Upvotes: 4
Views: 3020
Reputation: 620
I was able to work around this issue by adding the API call to a different thread, this avoids the main application from hanging. then add a time out or specific condition to close the thread
Upvotes: 0
Reputation: 1
You can fix it with BackgroundWorker
.
If the browser has been closed, the background_RunWorkerCompleted
will be fired.
Don't forget to use FileDataStore
,
because you can't get the credential variable from BackgroundWorker
.
Upvotes: 0
Reputation: 1705
It is not possible, in general, to detect when the user has closed the browser window/tab. For example, if the user is already running their default browser, then GoogleWebAuthorizationBroker opens a new tab, this is not running in the process started in LocalServerCodeReceiver. That new process terminates immediately.
However, currently the CancellationToken passed to GoogleWebAuthorizationBroker.AuthorizeAsync is not honoured whilst waiting for the auth response, meaning even trying to use a simple timeout doesn't work. #968 filed to fix this.
Upvotes: 0
Reputation: 116968
This is a known issue in the Google .net Client library.
There is currently no workaround that I know of. I recommend adding your name to the issues on the forum to encourage the team to address the issue.
Update: Its now on the list GoogleWebAuthorizationBroker does not honour CancellationToken when waiting for browser response
Upvotes: 2