How to connect to the G Suite APIs using a service account key with Node.js
Recently I needed to set the Gmail signature for all the users in the business. I found a number of tools online to do this, but they all seemed bloated with subscription based features cost I simply can’t justify.
All I needed was an easy way to set our users’ signatures, so I set out to write my own utility to do this. I used Node.js to connect to the Gmail API using a Service Account Key. Below is an example of how I got this working.
TLDR: Scroll to the bottom if you just want to see the example code.
Getting set up in Google Cloud Platform and G Suite
- Head over to the GCP console and make a new project. You can call it anything you like.
- Next go to the APIs & Services Dashboard:
3. Next click “Enable APIs and Services”:
4. Now search for “Gmail”, then click the Gmail API and enable it.
5. Next go to the Credentials page under APIs and Services:
6. In here, click “Create credentials” then “Service account key”. You can use whatever name you like. The private key for the service account will download once you finish, keep this in a safe place as you will need it soon.
7.Next copy your service account email address:
8. Now head over to the G Suite Admin portal and head to Security > Advanced Settings > Manage API Client access
9. Register a new API client by pasting the service account email address into client name and entering the scope you need. In my case I was setting email signatures on behalf of users, so I needed the scope https://www.googleapis.com/auth/gmail.settings.basic
Note that it can take some time for the new authorised API client’s permissions to take effect.
Connecting with Node.js
Now that your Service Account Key is set up in GCP and G Suite we can connect with Node.js. To do this we use the private key for the service account (downloaded in step 6) to form a JWT client which we will use for authentication with subsequent requests.
A key concept to understand when using a Service Account Key for authentication is that your JWT client only allows you to impersonate a user and make changes to their account on their behalf. Your JWT client does not give you God like admin powers to change any setting for any user.
When you create your JWT client you must specify which user you will be impersonating. And every time that you would like to impersonate another user, you must recreate your JWT and specify the new user to impersonate.