Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Revision as of 11:01, 27 June 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Google+ authentication in Windows Phone application

From Wiki
Jump to: navigation, search

This article demonstrates how to implement Google+ OAuth2.0 authentication and fetch user data on Windows Phone, without using a third party library.

Note.pngNote: Google provides a OAuth2.0 .Net Client Library that can be used to access Google+ services. The author has not tried this library.

WP Metro Icon Web.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone SDK 8.0, Windows Phone 7.1 SDK
Devices(s): Nokia Lumia 820, Lumia 920, Nokia Lumia 800
Platform(s): Windows Phone 8.0/ 7.1
Windows Phone 8
Windows Phone 7.5
Platform Security
Signing Required: Self-Signed
Keywords: Google+, Social Networking
Created: somnathbanik (30 Aug 2012)
Last edited: hamishwillee (27 Jun 2013)



Google+ OAuth2.0 authentication authorizes third party applications to access user data and other Google+ features using the Google+ API. In this article we will create an application which will authenticate and authorize an application to access user profile information.


Create an empty Windows Phone Project

Launch Visual Studio -> click on File->New Project-> select Windows Phone Application (Visual C# Template) -> add Name and Location of the project -> click OK to create the project.

Register your application with Google

To access Google+ API your application much be registered through Google APIs Console. If you are using the console for the first time and have never created any Google App before, then here are the steps for you:

  • Go to Google APIs Console
  • Click on the blue button Create Project
  • This will open the list of all Google API Services.
  • Switch ON the Google+ API service from the list and accept the license agreement.
  • Now go to API Access tab in the left panel.
  • Click on the blue button Create an OAuth2.0 client ID
  • Enter the Product Name (this is the name of your application, GoogleWp7OAuth is the app name used in this article), Product Logo (optional) and click Next
  • Select Installed Application from the application type and click on Create Client Id button.
  • This will create Client ID, Client secret and Redirected URIs of the application. Copy the set values for future use.

See Google APIs Console Help for more information about about creating and managing projects the console.

Adding controls on application page

In our application we have two pages MainPage.xaml and GooglePlusLoginPage.xaml. MainPage.xaml consist of one Button, three TextBlock and a Image control.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Login " Height="72" HorizontalAlignment="Left" Margin="31,517,0,0" Name="buttonLogin" VerticalAlignment="Top" Width="393" Click="buttonLogin_Click" />
<Image Height="238" HorizontalAlignment="Left" Margin="31,48,0,0" Name="imageGooglePlusUserPicture" Stretch="Fill" VerticalAlignment="Top" Width="234" />
<TextBlock Height="74" HorizontalAlignment="Left" Margin="31,309,0,0" Name="textBlockGooglePlusUserName" Text="" VerticalAlignment="Top" Width="393" FontFamily="Segoe WP" FontSize="45"/>
<TextBlock Height="30" HorizontalAlignment="Right" Margin="0,402,32,0" Name="textBlockGooglePlusUserEmail" Text="" VerticalAlignment="Top" Width="393" FontFamily="Segoe WP" FontSize="25" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="31,452,0,0" Name="textBlockGooglePlusUserGender" Text="" VerticalAlignment="Top" Width="393" FontFamily="Segoe WP" FontSize="25" />

The three TextBlock displays user name, email and gender, and the Image control displays the user profile picture. The Button control in MainPage.xaml is used to navigate to GooglePlusLoginPage.xaml which has a WebBrowser control to load the Google+ login page.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0,0">
<phone:WebBrowser HorizontalAlignment="Left" Margin="0,0,0,0" Name="webBrowserGooglePlusLogin" VerticalAlignment="Top" Height="800" Width="480" Navigated="webBrowserGooglePlusLogin_Navigated" Navigating="webBrowserGooglePlusLogin_Navigating" />

When the Google+ login is successful the page GooglePlusLoginPage.xaml gets closed and the control goes back to MainPage.xaml which then displays user’s name, email, gender and profile picture.

Launching Google+ login page

When user clicks on Login Button of the MainPage.xaml it navigates to GooglePlusLoginPage.xaml which then launch the WebBrowser and loads the Google+ login dialog.

//load google plus login page
void GooglePlus_LoginPage_Loaded(object sender, RoutedEventArgs e)
var url = "" +RedirctedUri+ "&scope=" + ClientId;
webBrowserGooglePlusLogin.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));

After user enters Google+ credentials it asks for application authentication. In this page you will see the name (GoogleWp7OAuth in this example) of your application requesting for permission to access user’s information.

Get the Authorization Code and Access Token

When user clicks on the Allow access button on the application permission page, the Google server returns an authorization code to the application either in the title bar of the browser or as a query string parameter to http://localhost which depends on the parameter sent in the request. For more information, see Choosing a Redirect URI.

We have used the parameter http://localhost for redirect_uri in #1 so that we get authorization code as a query string parameter. The following code receives an authorization code from Google server as a query string parameter when the user grants permission to your application.

   private void webBrowserGooglePlusLogin_Navigating(object sender, NavigatingEventArgs e)
if (e.Uri.Host.Equals("localhost"))
webBrowserGooglePlusLogin.Visibility = Visibility.Collapsed;
e.Cancel = true;
int pos = e.Uri.Query.IndexOf("=");
//get the access code
string messageCode = pos > -1 ? e.Uri.Query.Substring(pos + 1) : null;
//when code is not equeals to null get the access token
if (messageCode != null)
//get the access token
Parameters = "code=" + messageCode + "&client_id=" + ClientId + "&client_secret=" + ClientSecret + "&redirect_uri=" + RedirctedUri + "&grant_type=authorization_code";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start web request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);

We get the authorization code from the query string and assign it to a string variable called messageCode. Once the application receives the authorization code it then sends a HTTP Post request to get the access token and refresh token. To learn more on HTTP post request parameters used to get access token and refresh token as a response, see Handling the Response.

The Refresh Token is used to generate a new access token when it expires (this is an optional feature and is not needed to implement in this example for application authentication). See Using a Refresh Token for more information. When we get the response we then parse the access token for future use.

   void GetResponseCallback(IAsyncResult asynchronousResult)
var request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
using (var streamResponse = resp.GetResponseStream())
var GooglePlusSerializerData = new DataContractJsonSerializer(typeof(GooglePlusAccessToken));
var GooglePlusProfileData = GooglePlusSerializerData.ReadObject(streamResponse) as GooglePlusAccessToken;
(Action<GooglePlusAccessToken>)((GooglePlusUserData) =>
//save the response
thisApp.AccessToken = googlePlusTokens.AccessToken= GooglePlusUserData.AccessToken;
googlePlusTokens.RefreshToken = GooglePlusUserData.RefreshToken;
googlePlusTokens.ExpiresIn = GooglePlusUserData.ExpiresIn;
googlePlusTokens.TokenType = GooglePlusUserData.TokenType;
// request user profile
}), GooglePlusProfileData);
catch (WebException ex)

Load Google+ User Profile

RequestForUserProfile() method puts a web request with access token and gets the basic user’s information like name, email, gender, profile picture, birthday etc. by Calling Google+ API

//request for user prifile
void RequestForUserProfile()
// var urlProfile = "" + thisApp.AccessToken;
var urlProfile = ""+thisApp.AccessToken;
// web request user profile
WebRequest request = WebRequest.Create(urlProfile);
request.BeginGetResponse(new AsyncCallback(this.ResponseCallbackProfile), request);

We catch the asynchronous call at ResponseCallbackProfile() and parse the user’s information and display it on the MainPage.xaml page.

// user profile response 
private void ResponseCallbackProfile(IAsyncResult asynchronousResult)
var request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
using (var streamResponse = resp.GetResponseStream())
var GooglePlusSerializerData = new DataContractJsonSerializer(typeof(GooglePlusUserProfile));
var GooglePlusProfileData = GooglePlusSerializerData.ReadObject(streamResponse) as GooglePlusUserProfile;
(Action<GooglePlusUserProfile>)((GooglePlusUserData) =>
thisApp.UserName= googlePlusUserInfo.UserName =;
thisApp.UserImage = googlePlusUserInfo.UserPicture = GooglePlusUserData.picture;
if (thisApp.UserImage == null)
thisApp.UserImage = googlePlusUserInfo.UserPicture= "";
googlePlusUserInfo.UserBidthday = GooglePlusUserData.birthday;
thisApp.UserEmail= googlePlusUserInfo.UserEmail =;
googlePlusUserInfo.UserFamilyName = GooglePlusUserData.family_name;
thisApp.UserGender= googlePlusUserInfo.UserGender= GooglePlusUserData.gender;
Deployment.Current.Dispatcher.BeginInvoke(() =>
}), GooglePlusProfileData);
catch (WebException ex)

Note.pngNote: To run the code make sure you have replaced <Your Client ID> with Client ID and <Your Client Secret> with Client secret that you got from Google APIs Console.


The goal of this example is to show Google+ OAuth2.0 authentication without using any third party library. Applications can also be authenticated using Google API key. To learn more, see Google Authorization Protocol .

Related Article

Source Code

  • The full source code of the example is available here:
  • If you are in a hurry to test the application, unzip the source code and install the binary file from the given location: GooglePlusAuthentication->Bin->Release->GooglePlusAuthentication.xap
This page was last modified on 27 June 2013, at 11:01.
303 page views in the last 30 days.