Question

I am building a Windows 8 application and I'm trying to get a token from the Google data API when the application is starting. I built a function to do this, and it has the following code:

string authCodeUrl = UrlHelpers.BaseUrlFactory(UrlType.OAuth) +
                    "?client_id=" + _clientId +
                    "&redirect_uri=" + _redirectUri +
                    "&response_type=code" +
                    "&scope=" + _scope;

Uri startUri = new Uri(authCodeUrl);
Uri endUri = new Uri("https://accounts.google.com/o/oauth2/approval?");

WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);

I'm calling the function in my App.xaml.cs OnLaunched(), before the Window.Current.Activate() call. The reason I am doing this is because I already need the token in my MainViewModel.

The strange thing is: when I launch my application the normal way (via Visual Studio) it gets stuck at the splashscreen (the splashscreen stays on for ages), but when I place a breakpoint on this line:

WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);

and step through it, I suddenly get a log in window that allows me to log in and obtain a token, meaning that the splashscreen goes away and I can use my application.

When I remove the call from my App.xaml.cs and just request the token from my ViewModel, I have the same problem: it's still stuck on the SplashScreen. I also have this problem when I do request a token from my App.xaml.cs but move the request after the Window.Current.Activate() call. But in these cases, the splashscreen goes away after logging in, but the screen stays black. I don't see my app.

P.s., this is how I request the token from my App.xaml.cs (OnLaunched is marked as async):

IOAuth2Service oAuth2Service = new OAuth2Service();
await oAuth2Service.GetToken();

OAuth2Service is just an object that has a method GetToken(). This method just does what I described above.

Does anyone know why it works when I step through the app with a breakpoint, but not when I just launch it without stepping through it?

I've isolated the problem and created a Github project that contains just this code. You can find it here: https://github.com/Avalaxy/OAuth2WinRT/tree/master/App1. There is an app.xaml.cs which calls OAuth2.GetToken().

Était-ce utile?

La solution

Per the documentation -

If the app or its splash screen is kept on screen there is no time limit, but eventually the app needs to call Activate to progress.

Admittedly a bit vague and subject to interpretation, but moving the call to activate prior to the GetToken request will get you past what seems like a potential race condition.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top