Easy Guide on how to use OAuth to Access Google APIs

By | March 10, 2016

Nearly a year ago Google already deprecated a most of its legacy API’s which means you cannot authenticate using the Google.GData.Client.Service and executing the setUsersCredentials method and simply indicating your user and password.  It was changed with OAuth making it more secure as it uses tokens and let the user actually log in to Google’s servers to perform the initial authentication and generation of tokens.

This means gone are the days of quick and easy way of authenticating your user instead you will be performing multiple steps to perform the authentication.  This article will explain to you step by step on just how to achieve that in the most easiest way.  For this article we will be creating a simple password reset of a user in Google which is very useful when you want to revoke access for a user in your domain but leaving the account readable as long as you have the password.  The codes that I will be showing has also the capability of updating your user information as we are using the UsersResource in Google’s Directory Service meaning any user information exposed on this object can be manipulated.

But before we start I am assuming that you will be using a user with a Vault administrator access across your domain so it can perform needed action on any users on your domain.  So I suggest before you continue secure that access or check whether you have one.  To verify this go an manage your domain

0 Mange Domain

and see if you have this lock icon used for resetting a password on any user you want to modify

0 Reset Password Check

If you have it then you can continue otherwise ask for that access first before continuing.  Now lets start!

1. Create a Project in Google’s Developer Console

Go to https://console.developers.google.com/ and log in using your user that has the Vault administrator access.   Once in create a new project and give it a meaningful name.

00a Create a Project

After it was created go to OAuth consent screen

00b Project Created

And set a product name shown to users.  This is what will be shown to users whenever you request access to their private data.

00c Assign a Product Name

Then go to credentials and create one

00d Create Credentials

Choose OAuth client ID

00e Create Credentials OAuth

then choose other and give it a name

00f Create User

Once created you will be given a client Id and a secret token.

00g Client Secret Created

Now you can download that token so that you can use it in the application you are developing

00h Client Secret For Download

The download basically is a JSON file which contains your Client Id and other details about your project as well as the client_secret

00i Json File

So this is where it got its data

00j What is in the Json File

2. Lets create your project or at least the class you need.

First you need the references to the APIs that you will be using so using Nuget install the Google APIs Client Library

01 Nuget References

As well as Google APIs Admin Directory

02 Apis Directory

Other dependencies will be installed so at a minimum you will need them.  Take note you might need to update other references for this to work so in the Manage Nuget Packages screen on the left hand menu choose updates and update all.

Now lets start coding, for this demo we will just put it in one class to simplify, up to you how would you structure it for your project.

using System;
using System.IO;
using System.Net;
using System.Threading;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
 
namespace GoogleOAuthDemo
{
    public class GoogleUser
    {
        static readonly string[] Scopes = { DirectoryService.Scope.AdminDirectoryUser };
        private const string ApplicationName = "Google Directory API Demo";
        private const string ClientSecretJsonFile = "client_secret.json";
        private const string GoogleFolder = "Google";
 
        public static void RunPasswordReset(string userEmailStringstring userPassword)
        {
            try
            {
                //Set location for Google Token to be locally stored
                var googleTokenLocation = Path.Combine(Environment.CurrentDirectoryGoogleFolder);
 
                //Load the Client Configuration in JSON Format as a stream which is used for API Calls
                var fileStream = new FileStream(Path.Combine(Environment.CurrentDirectoryClientSecretJsonFile), FileMode.OpenFileAccess.Read);
 
                //This will create a Token Response User File on the GoogleFolder indicated on your Application
                var credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(fileStream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                  new FileDataStore(googleTokenLocation)).Result;
 
                //Create Directory API service.
                var directoryService = new DirectoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = ApplicationName
                });
 
                //Email is considered the Primary on Google Accoutns
                var userkey = userEmailString;
 
                //Set User attributes, in this example the password.
                var userBody = new User
                {
                    Password = userPassword
                };
 
                //Prepares the update request
                var updateRequest = directoryService.Users.Update(userBodyuserkey);
 
                //Executes the update request
                updateRequest.Execute();
            }
            catch (Exception ex)
            {
                //Add you exception here
            }
        }
    }
}

If you see from the codes we have indicated where you will be storing your client secret JSON file.  We also had indicated a location where Google will store the Token response file.  This file gets updated once it expires and you need to make sure the user running the application can read and write both file and folder locations.

From here its quite simple, you will not see any user and password unlike the old authentication mechanism, the JSON file identifies you and when you first run the application you will need to sign in as the user you used in generating the secret file.  This way its more secure.

From here you can basically do anything with the user,  so I leave it up to you what you want but for this sample I will just do a change password.

xx User Object

That’s it you can run call that method RunPassword reset like such

GoogleUser.RunPasswordReset("testuser@test.com""s0m3R4nd0mP455w0rd!");

3. Authorizing for the Application for the first time.

On the first instance you run the codes, when you call that AuthorizeAsync
it will open your default browser (make sure sign out every Google account before running your app) and ask you for your credentials

Enter the user’s email (still that user with Vault admin access) and password

03 Oauth Trigger First Time

It will then ask you whether you want to allow that application to have access using your credentials.

04 Oauth Permission

Once you allowed it will create a token on your GoogleFolder that you nominated on your codes.

05 File Created

And the browser will give you a return message that you received the verification code.

06 Oauth Authorized

On succeeding runs this will not do this anymore unless you revoke the applications access.  Another layer for security.

4. Managing the Application Access

Go to https://myaccount.google.com/security, using the same user go to the section where it says Connected apps & sites.  You will see here the application you just developed.

07 Check Apps

From here you can manage it and remove its access.

08 Remove Access

That app only will show here once a token is created.

That it, it’s that simple.

 

Recommended

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.