How to create a JWT token from Google Cloud Service Account Key

Rajathithan Rajasekar
1 min readDec 8, 2021
photo by @mak_jp at unplash

In this post, we are going to see how to generate the JWT token using Python from a google cloud service account key. To identify a service that sends requests to your API, you use a service account. The calling service uses the service account’s private key to sign a secure JSON Web Token (JWT) and sends the signed JWT in the request to your API.

Follow the below steps

Step: 1

Import the necessary packages

from google.auth import cryptfrom google.auth import jwtimport osimport ioimport jsonimport time

Step: 2

Define the service account credential path

# Service account key pathcredential_path = "service-account-key.json"os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path

Step: 3

Define the keyfile path, service-account email address, audience and expiry_length (TTL)

Step: 4

Create the payload with time, expiry, issuer, audience, email address

Step: 5

Using the crypt library sign with the key file

Step : 6

Using the jwt library encode the signer with the payload file.

Step : 7

Retrieve the JWT token.

The gihub gist is given below for your reference.

Thanks for reading this post, I hope it was useful.

Rajathithan Rajasekar

I like to write code in Python . Interested in cloud , dataAnalysis, computerVision, ML and deepLearning.