Implementing Google Contacts API Version 3.0 & OAuth 2.0 in cSharp and ASP.NET [Updated]

Implementing Google Contacts API Version 3.0 & OAuth 2.0 in cSharp and ASP.NET [Updated]

In this tutorial I will develop a web application to get all Google Contacts from a person account who authorizes the application. I will make it in Asp.Net platform and will use C# to communicate with the Google Contacts API.

Another tutorial on Yahoo API explains how to programmatically export your Yahoo Contacts.

To implement Google Contacts API, first you have to create a project in Google APP console, and create credentials for accessing it. The following 3 steps will explains this, later I will use this project to communicate with my C# code.

STEP 1 – Create Project and Enable Google Contacts API

The first step is to create API Project in Google APP Console:

  • a. Visit https://console.developers.google.com/cloud-resource-manager.
  • b. Click Create Project button. creating project in google console
  • c. Give your project some name and click the Create Button. This will create your project. The project will be created after a few second. Refresh the page with F5 key and you will see your created project name there. new project in google console
  • d. Click on the project to reach the IAM & Admin area. There, click the Google APIs logo on the top left corner of the screen. This takes you to Google APIs Library page. click google apis logo
  • e. You will see all Google API there. Find Contacts API link and click on it. google contacts api
  • f. Click the Enable button to enable Google Contact API. Enable Google Contact API
Would you like to dig deep into the world of database programming with C#? Then you can check this series of tutorials on Entity Framework Core that help you to learn database programming within a few hours time.

STEP 2 – OAuth Consent Screen

On the same page (Google APIs Library page), click ‘Credentials’ link then click OAuth Consent Screen.

In this page add your Product Name and click the ‘Save’ button.

<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/oauth-consent-screen.png" alt="oauth consent screen" class="img-fluid">

STEP 3 – Create Credentials & Client ID

Next, Google asks you to Create Credentials. Here click on the Create Credentials button (which will show some options on clicking). Select the option that says OAuth Client ID.

<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/create-credentials.png" alt="create credentials" class="img-fluid">

Next, it will ask to select the Application Type. Here select Web Application and give na ame to your Application.

For the Authorised redirect URIs field, enter the URL where users will be redirected once authenticated with Google.

Finally click the ‘Create’ button.

<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/create-client-id.png" alt="create client id" class="img-fluid">

Google will create the Application and give you the Client ID and Client Secret.

Save them securely, we will use them later in our application.

<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/client-id-and-client-secret.png" alt="client id and client secret" class="img-fluid">
My Project in Google App Console is created. Next we have to communicate with it using C#. I will use OAuth 2.0 to authenticate users with this project.

Google OAuth 2.0 Working

OAuth 2.0 authenticates the users and asks for there permissions for sharing contacts with the application. If a user grants his permission then Google sends Authorization Code to the return URL in query string variable called code.

I would also recommend you to learn What is OAuth because it forms the backbone of this Google Contacts API application.
Google OAuth 2.0 Structure
Google OAuth 2.0

See Google OAuth 2.0 online doc at – here.

Let us create the ASP.NET Web Application. This application will communicate with the Google App and gets all emails addresses of the user’s contacts from his Google account.

Note: It will first ask for user’s consent to get all emails, and when the user allows it, only then the emails are shared.

Now follow the steps as I have outlined below:

STEP 1 – Authenticate User with Google OAuth 2.0 and ask for Permission

  • a. Redirect user to URL: https://accounts.google.com/o/oauth2/auth.
  • b. Pass the following query string parameters with the URL:
    redirect_uri – given by you when creating New Client ID in step 3 given above.
    response_type – code
    client_id – your client id
    scopehttps://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline

I will redirect user on a Button’s Click Event, so create a button and add the redirect code on its click event.

HTML

<asp:Button ID="googleButton" Text="Get Google Contacts" runat="server"
OnClick="googleButton_Click" />

C#

protected void googleButton_Click(object sender, EventArgs e)
{
    string clientId = "ClientId";
    string redirectUrl = "https://www.demo.yogihosting.com/aspnet/
        google-contacts-api/index.aspx";
    Response.Redirect("https://accounts.google.com/o/oauth2/auth?
        redirect_uri="+redirectUrl+"&response_type=code
        &client_id=" + clientId + "&scope=
        https://www.google.com/m8/feeds/&approval_prompt=
        force&access_type=offline");
}

I have kept the redirect URL to the same page where the button is placed. Note that it must be the same which we put in for Authorised redirect URIs field when creating the Client ID.

Testing

Run the web page in your browser and click the button. Google will show the Consent Screen and ask you to grant permission to the Google Project which I created before.

Click the Allow Button and you will be redirect to the URL set by you earlier.

<img src="https://www.yogihosting.com/wp-content/uploads/2015/02/consent-screen.png" alt="consent screen" class="img-fluid">

STEP 2 – Exchange Authorization Code to get Access Code

Here we have to make HTTP POST request to the URL: https://accounts.google.com/o/oauth2/token, and must pass the following parameters with it –

  • a. code: authorization code
  • b. client_id: client id of application
  • c. client_secret: client secret of application
  • d. redirect_url: One of the redirect URIs listed for this project
  • e. grant_type: authorization_code
A successful response will return the following things in JSON format –
  • a. access_token: the token from which Google API call can be made
  • b. refresh_token: the token which is used to generate new Access Token when the current one expires
  • c. expires_in: the life time of Access Token
  • d. token_type: type of token returned, in our case it will be bearer

The redirect URL will contain the Authorization Code in the query string parameter (code) so we put a check in Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["code"] != null)
        GetAccessToken();
}

It will call the GetAccessToken() function which will get the Access and Refresh Tokens.

public void GetAccessToken()
{
    string code = Request.QueryString["code"];
    string google_client_id = "ClientId";
    string google_client_sceret = "ClientSecret";
    string google_redirect_url = "https://www.demo.yogihosting.com/aspnet/
      Google-Contacts-API/index.aspx";
 
    /*Get Access Token and Refresh Token*/
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create
      ("https://accounts.google.com/o/oauth2/token");
    webRequest.Method = "POST";
    string parameters = "code=" + code + "&client_id=" + google_client_id + 
      "&client_secret=" + google_client_sceret + "&redirect_uri="
      + google_redirect_url + "&grant_type=authorization_code";
    byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = byteArray.Length;
    Stream postStream = webRequest.GetRequestStream();
 
    // Add the post data to the web request
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();
    WebResponse response = webRequest.GetResponse();
    postStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(postStream);
    string responseFromServer = reader.ReadToEnd();
    GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject
      <GooglePlusAccessToken>(responseFromServer);
    /*End*/
 
    GetContacts(serStatus);
}

Note the last couple of lines, I get response in JSON that also contains Access and Refresh tokens. So I used Json.NET to extract these values and put it inside the GooglePlusAccessToken class like this.

GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject
  <GooglePlusAccessToken>(responseFromServer);

The GooglePlusAccessToken class:

public class GooglePlusAccessToken
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
}

In the end this function I call the GetContacts() function whose work is to make Google Contacts API call.

STEP 3 – Make Google API Calls with the Access Token to get Users Contacts

Add a div to the .aspx page.

<div id="dataDiv" runat="server"></div>

Please note that in this step I have used a few Google dot net dlls for making the API call. It simplifies the approach. You will find this in the download code.

The URL to make API call is https://www.google.com/m8/feeds/contacts/{userEmail}/full.

Just pass ‘default’ for userEmail, ‘default’ refers the authenticated user.

The definition of the GetContacts() function is:

public void GetContacts(GooglePlusAccessToken serStatus)
{
    /*Get Google Contacts From Access Token and Refresh Token*/
    string refreshToken = serStatus.refresh_token;
    string accessToken = serStatus.access_token;
    string scopes = "https://www.google.com/m8/feeds/contacts/
      default/full/";
    OAuth2Parameters oAuthparameters = new OAuth2Parameters()
    {
        Scope = scopes,
        AccessToken = accessToken,
        RefreshToken = refreshToken
    };
 
    RequestSettings settings = new RequestSettings
      ("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
    ContactsRequest cr = new ContactsRequest(settings);
    ContactsQuery query = new ContactsQuery(ContactsQuery
      .CreateContactsUri("default"));
    query.NumberToRetrieve = 5000;
    Feed<Contact> feed = cr.Get<Contact>(query);
 
    StringBuilder sb = new StringBuilder();
    int i = 1;
    foreach (Contact entry in feed.Entries)
    {
        foreach (EMail email in entry.Emails)
        {
            sb.Append("<span>"+ i + ". </span>").Append(email.Address)
              .Append("<br/>");
            i++;
        }
    }
    /*End*/
 
    dataDiv.InnerHtml = sb.ToString();
}

The user contacts data is send in JSON format, I extract it, and finally loop through this data and show it in a div.

Testing

Now click the button and once you give your consent you will see all your contacts email in the div control like shown in the below image.

contacts email
Conclusion

This completes our Google Contacts API application. Hope you like it and please share this tutorial in your FB and twitter accounts.

Download link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate