Search code examples
c#oauth-2.0windows-phone-8.1google-oauth

Google integation in windows phone 8.1[RT] application


I am working with windows phone 8.1 application and I want to login with Google Plus , for that I have create Client id and Client secret from Google

 string uri = string.Format("{0}?response_type=code&client_id={1}&redirect_uri={2}&scope={3}&approval_prompt=force",
            authEndpoint,
            clientId,
            "urn:ietf:wg:oauth:2.0:oob",
            scope);
 webBrowser.Navigate(new Uri(uri, UriKind.Absolute));

and I Got string something like 4/BGIl1Na3TQJlAD8SQ7blvHyONJ_Jyav8COHa7tIrAdo

I want User Email and Name from account for signup or login Please help me for that. Thank you


Solution

  • Implement the interafce IWebAuthenticationContinuable to your class and then under ContinueWebAuthentication() Method use this code :

    var authData = GetGoogleSuccessCode(args.WebAuthenticationResult.ResponseData); 
    var userData = await GetTokenAndUserInfo(authData);
    
    private string GetGoogleSuccessCode(string data)
            {
                if (string.IsNullOrEmpty(data)) return null;
                var parts = data.Split('&')[0].Split('=');
                for (int i = 0; i < parts.Length; ++i)
                {
                    if (parts[i] == "Success code")
                    {
                        return parts[i + 1];
                    }
                }
                return null;
            }
    
    public async Task<string> GetTokenAndUserInfo(string code)
            {
                var client = new HttpClient();
                var auth = await client.PostAsync("https://accounts.google.com/o/oauth2/token", new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("code", code),
                        new KeyValuePair<string, string>("client_id",Constants.GoogleAppId), 
                        new KeyValuePair<string, string>("client_secret",Constants.GoogleAppSecret), 
                        new KeyValuePair<string, string>("grant_type","authorization_code"),
                        new KeyValuePair<string, string>("redirect_uri","urn:ietf:wg:oauth:2.0:oob"),  
                    }));
    
                var data = await auth.Content.ReadAsStringAsync();
                var j = JToken.Parse(data);
                var token = j.SelectToken("access_token");
                var searchUrl = "https://www.googleapis.com/oauth2/v2/userinfo";
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.ToString());
                HttpResponseMessage res = await client.GetAsync(searchUrl);
                string content = await res.Content.ReadAsStringAsync();
                return content;
            }
    

    And add following code in App.xaml.cs file:

    public static ContinuationManager ContinuationManager { get; private set; }
    
    
     public App()
    {
        ContinuationManager = new ContinuationManager();
    }
    
    private void OnSuspending(object sender, SuspendingEventArgs e)
            {
                var deferral = e.SuspendingOperation.GetDeferral();
    #if WINDOWS_PHONE_APP
                ContinuationManager.MarkAsStale();
    #endif
                // TODO: Save application state and stop any background activity
                deferral.Complete();
            }
    
    protected override void OnActivated(IActivatedEventArgs args)
            {
    #if WINDOWS_PHONE_APP
                if (args.Kind == ActivationKind.WebAuthenticationBrokerContinuation)
                {
                    var continuationEventArgs = args as IContinuationActivatedEventArgs;
                    if (continuationEventArgs != null)
                    {
                        ContinuationManager.Continue(continuationEventArgs);
                        ContinuationManager.MarkAsStale();
                    }
    
                }
    #endif
            }
    

    Don't forget to include Continuation Manager class file in your project. You will get the user info.