Use Google service account to create OAuth 2.0 token and call Google API

In this blog, I will show you how you can create OAuth 2.0 token using Google service account and then call any Google API.

Create Google service acccount

To create Google service account, visit https://console.cloud.google.com/ and create project if project yet not created. Now in Quick access click on Api & Services and you will have the interface like this.

Now click on Credentials.

On visiting Credentials at the top, you will see + CREATE CREDENTIALS click on that.

Now create your service account.

After creating service account go inside that and create a new key by going to Keys Tab and click on Add KEY.

After creating, download the JSON file.

Create a python script with following code:-

Before running following code install service_account python library.

pip install google-auth

OR

pip install google-auth

from google.oauth2 import service_account
import google.auth
import google.auth.transport.requests

SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = './your_secret_key.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

auth_req = google.auth.transport.requests.Request()
credentials.refresh(auth_req)
print(credentials.token)

This script would print your OAuth access token.

To use any Google rest api just add this token as Bearer token.

for example:-

curl --location 'https://www.googleapis.com/calendar/v3/calendars/example%40gmail.com/events' \
--header 'Authorization: Bearer <Your_Access_Token>'

API to Test Access Token Info : https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<YOUR_ACCESS_TOKEN>

Permission Scopes List : https://developers.google.com/identity/protocols/oauth2/scopes

For more info visit https://google-auth.readthedocs.io/en/master/

Leave a Reply