How to authenticate through any Google API

The settings of the Google Developers Console may be complicated, which is one of the reasons why I sometimes do not want to use one of the Google APIs. This article aims to make it easy to use

This article describes how to use the Google Developers Console to authenticate to any Google API.

The developer console may be difficult to set up correctly, which is one of the reasons why I sometimes resist using a Google API.

Let's take a look at how it works in a very simple way.

This guide assumes that you already have a Google account.

Create a new Google API project

If it is not completed yet, please create a new project.

The Google API Dashboard

In the dashboard, clickCreate a new project.

Create a new API project

Give it a name and you will be redirected to the project dashboard:

The new project dashboard

Add API by clickingEnable API and services.

The API library

Search the API you are interested in from the list

Choose an API

And enable it

Enable an API

That's it!

The API is enabled

Now that the project is ready, you can proceed to create authentication credentials.

Create authentication credentials

There are 3 ways to use Google API for authentication:

  • OAuth 2
  • Service to service
  • API key

The security of the API key is poor, and it is restricted by Google in terms of scope and use.

OAuth 2 is designed to allow your app to make requests on behalf of the user, so the process is more complicated than necessary and requires public URLs to handle callbacks. Too simple, too complicated to use.

In the "service-to-service" authentication model, the application uses a service account and a JSON web token to directly talk to the Google API.

This is the easiest way, especially when you want to build a prototype or application that communicates with the Google API from a server (such as a Node.js application). This is one way I will test this article.

Service to Service API

To use this method, you need to first generate aJSON key fileThrough the Google Developers Console.

There is another option which involves downloading.p12File and convert it topemFile usageopensslcommand. Google no longer recommends,Just use JSON.

In the project dashboard, clickCreate credentialsAnd selectService account key:

Choose the type of credentials

Fill out the form and select the "JSON" key type:

Fill the form for credentials

That's it! Google sent you a JSON file:

The JSON file was saved

This is the content of this JSON file calledJSON key file:

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}

Use JSON key file

The easiest way is to put the JSON file on a file system accessible to the program.

For example, I have a test application~/dev/test, So I put the JSON file into that folder and renamed it toauth.json. Then inside the Node.js application, make sure that the GOOGLE_APPLICATION_CREDENTIALS environment variable points to the file location on the file system.

You create aJSON web tokenUse the attributes contained in the file:

const jwt = new google.auth.JWT(key.client_email, null, key.private_key, scopes)

And pass it on to any API requests you make.

This is an example of how to use it with the Google Analytics API.process.env.GOOGLE_APPLICATION_CREDENTIALSIt's best to set it outside the program, but for clarity, I added it in the source code:

'use strict'

const { google } = require(‘googleapis’)

const key = require(’./auth.json’) const scopes = https://www.googleapis.com/auth/analytics.readonly const jwt = new google.auth.JWT(key.client_email, null, key.private_key, scopes) const view_id = ‘XXXXXXX’

process.env.GOOGLE_APPLICATION_CREDENTIALS = ‘./auth.json’

jwt.authorize((err, response) => { google.analytics(‘v3’).data.ga.get( { auth: jwt, ids: ‘ga:’ + view_id, ‘start-date’: ‘30daysAgo’, ‘end-date’: ‘today’, metrics: ‘ga:pageviews’ }, (err, result) => { console.log(err, result) } ) })

Use environment variables

In many cases, this is not ideal, in which case it is impractical or unsafe to have your private information on the file system. For example, if you are using Heroku, it is best to avoid putting authentication credentials in the repository, and instead set up through the interface or console provided by Heroku.

Still use it aboveglitchPrototype, where environment variables are hidden from everyone except you.

In this case, the best way is to use environment variables and store the required content in the JSON file. In the following example, what we need isclient_emailwithprivate_keyVariables set in JSON, so we can extract these variables and set them as environment variables to keep them private.

'use strict'

const { google } = require(‘googleapis’)

const scopes = https://www.googleapis.com/auth/analytics.readonly const jwt = new google.auth.JWT( process.env.CLIENT_EMAIL, null, process.env.PRIVATE_KEY, scopes ) const view_id = ‘XXXXXXX’

jwt.authorize((err, response) => { google.analytics(‘v3’).data.ga.get( { auth: jwt, ids: ‘ga:’ + view_id, ‘start-date’: ‘30daysAgo’, ‘end-date’: ‘today’, metrics: ‘ga:pageviews’ }, (err, result) => { console.log(err, result) } ) })

Access other API

I used Google Analytics in the example.

ThisgoogleObject makes it reachablegoogle.analytics('v3').

v3Is the API version.

Other APIs can be accessed in a similar way:

  • google.urlshortener('v1')
  • google.drive('v2')

More service tutorials: