Authenticating & Calling Google Cloud Function with Service Account
Tags: python, google, cloud, cloudfunctions
Published: 2020-09-07 14:47:50

---
title: Authenticating & Calling Google Cloud Function with Service Account
published: true
description: The post gives a step by step way to authenticate a google cloud function using a service account
tags: #python #google #cloud #cloudfunctions
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/yifj2vp1u5hpq6lyh9zg.jpg
---
(Cover Image from [here](https://unsplash.com/@cdr6934))

The services from Google Cloud have been around for a while. Google Cloud Functions is a serverless, event-driven service within Google Cloud Platform meant to create and implement programmatic functions within Google's public cloud.

All infrastructure resources are provisioned and recovered automatically by Google Cloud Platform (GCP). The GCP also gives a good list of console commands to work with them. 

###Authenticating Cloud Functions
There are various scenarios which are applicable for authenticating the functions. One such scenario for me for authenticating user Service account.

At this point of time, I am assuming you already have a service account created. For the very first step to start with, add your service account to IAM. For this Navigate to IAM on your GCP, and click on Add
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vermj2ul91qd6aaou8vx.PNG)

Once you do that, there will be an input for member name. Put your service account name there. Next we will add roles to this service account.

To authenticate a could service using service account, make sure your service account has these roles
1. Service Account Token Creator
2. Service Account User
3. Service Usage Consumer

Click on Save to save your data.

One last setup before we jump to the code for generating token is generating keys for the Service Account. Navigate to the service accounts on your GCP. Under the list, that shows the service accounts, click on the Create Key option. This should download a .json file that will have the key information. This is an imp file that has sensitive information. For more, refer [here](https://cloud.google.com/iam/docs/creating-managing-service-account-keys#iam-service-account-keys-create-console)

Our service account is now setup. Now we need to get an auth token for this service account. This generated token, can then be used to call a GCP service that is using auth as service account. I had used a google cloud function in my scenario. Make sure the service we are trying to access, has the same service account set. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wprcaaemevf16uwdvimd.PNG)

Now lets look the code snippet that will generate a JWT Token for us.
```
from google.oauth2 import id_token
from google.oauth2 import service_account
import google.auth
import google.auth.transport.requests
from google.auth.transport.requests import AuthorizedSession
import requests

# path to your cloud function or any other service
url = 'https://{region}-{project-id}.cloudfunctions.net/{cloud-function-name}'

# path to you keys file that was downloaded when keys for SA were created
keyFilePath = 'key.json'
creds = service_account.IDTokenCredentials.from_service_account_file
(keyFilePath,
target_audience=url)
# auth session
authed_session = AuthorizedSession(creds)

# make authenticated request and print the response, status_code
resp = authed_session.get(url)

# to verify an ID Token
request = google.auth.transport.requests.Request()
token = creds.token
# print the generated token
print(token)
print(id_token.verify_token(token,request))
```
This should give you the JWT token which will be required to authenticate the subsequent requests. All you have to do is pass this token in the headers when calling the respective cloud service.
```
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer {token}'.format(token = token)
}
```

Using these steps we can get a token and then call a service hosted on GCP. The same code and steps can be used to call a GCP cloud function from AWS Lambda or any other HTTP Request.