Using Google Oauth2 to Access Google User Data from Client Application

using System;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Oauth2.v2;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Oauth2.v2.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Contacts;
using Google.Contacts;
namespace EmailClient

public class GmailLogin {
private static string xoauthKey;
private static string userEmail;
private static string userName;
private static UserCredential credential;
private static string[] contacts;
private static string[,]contactDetails;
private static int totContacts;
private static ContactsRequest cr;
private static readonly GmailLogin
m_Instance =new


// Prevent instance creation from other classes using singleton design pattern
private GmailLogin() {

public static GmailLogin Instance

get {
return m_Instance;

public bool GoogleLogin() {
// Request Gmail IMAP/SMTP scope and the e-mail address scope.
string[] scopes = new string[]{ “https:
//”, Oauth2Service.Scope.UserinfoEmail, Oauth2Service.Scope.UserinfoProfile, “" };
Console.WriteLine(“Requesting authorization”);
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
ClientId = “specify your client_ID here”,
ClientSecret = “specify your client_secret here”,
Console.WriteLine(“Authorization granted or not required( if the saved access token
already available)”);
* access token is also saved locally in a persistent location
* C:\Users\UserName\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user
* for later use.
if (credential.Token.IsExpired(credential.Flow.Clock)) {
Console.WriteLine(“The access token has expired, refreshing it”);
try {
if (credential.RefreshTokenAsync(CancellationToken.None).Result) {
Console.WriteLine(“The access token is now refreshed”);
return true;
} else {
Console.WriteLine(“The access token has expired but we can’t refresh it”);
return false;
} catch (Exception ex) {
return false;
} else {
Console.WriteLine(“The access token is OK, continue”);
return true;

public void RequestEmail() {
Console.WriteLine(“Requesting the e - mail address of the user from Google”);

Oauth2Service oauthService = new Oauth2Service(
new BaseClientService.Initializer() {
HttpClientInitializer =GmailLogin.getCredential()
Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result;
userEmail = userInfo.Email;
userName = userInfo.Name;
Console.WriteLine(“E - mail address is “ + userEmail);
//to access user’s contact list
RequestSettings settings = new RequestSettings(“Google Sync.”, GmailLogin.getCredential().Token.AccessToken) {
AutoPaging =true,
UseSSL =true
cr = new ContactsRequest(settings);
FetchAllContacts(cr, userEmail);

// Build XOAUTH2 token to use Gmail IMAP or SMTP.
xoauthKey = OAuth2.GetXOAuthKeyStatic(userEmail, GmailLogin.getCredential().Token.AccessToken);
// return true;

public void RevokeAccessToken() {
FileDataStore ds = new FileDataStore(GoogleWebAuthorizationBroker.Folder);
ds.DeleteAsync<TokenResponse> (“user”).Wait();

public static string getUserEmail() {
return userEmail;

public void FetchAllContacts(ContactsRequest cr, String email) {
Feed<Contact> feed = cr.GetContacts(email);
int i = 0;
contacts = new string[feed.TotalResults];
contactDetails = new string[feed.TotalResults, 3];
totContacts = feed.TotalResults;
foreach(Contact entry in feed.Entries)
contactDetails[i, 0] =entry.Id;
contactDetails[i, 1] =entry.Name.FullName;

foreach(EMail e in entry.Emails)
Console.WriteLine(“\t” + e.Address);
contacts[i] = e.Address;
// Console.WriteLine(contacts[i]);
contactDetails[i, 2] =e.Address;

public static string[] getContacts() {
return contacts;

public static string[,]

getContactDetails() {
return contactDetails;

public static string getUserName() {
return userName;

public static string getOauthKey() {
return xoauthKey;

public static int getTotContacts() {
return totContacts;

public static bool DeleteContact(Uri contactURL) {
// Retrieving the contact is required in order to get the Etag.
Contact contact = cr.Retrieve < Contact > (contactURL);
try {
return true;
} catch (GDataVersionConflictException e) {
return false;

public static UserCredential getCredential() {
return credential;




Software Engineer | GSoC Intern | CSE Graduate

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

And the next you’re perfectly in flow writing the most important book of your entire career.

Tips to successfully build your open-source projects #7. Promote

Ready to integrate Python with Tableau?

How To Develop An App Like Coursera | App Development Guide

2020’s Most Popular Programming Languages for UI Test Automation


5 Performance Management Tips in the times of Corona — Vol.2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sathya Bandara

Sathya Bandara

Software Engineer | GSoC Intern | CSE Graduate

More from Medium

Enterprise Application Architect- Part 1

Create a Hello World web app for Azure App Service using the Azure Toolkit for Eclipse

All things microservices (Part II)

Feature Toggles for Spring Boot applications with IBM Cloud App Configuration