Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Google Cloud Function from python using service account for authentication

I have a cloud function with trigger type set to HTTP and also have a service account which is having permissions to Invoke the cloud function. I want to invoke the cloud function from a python script. I am using the following script to invoke the function:

from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

credentials = service_account.Credentials.from_service_account_file('/path/to/service-account-credentials.json')

scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/cloud-platform'])

authed_http = AuthorizedHttp(scoped_credentials)

response = authed_http.request('GET', 'https://test-123456.cloudfunctions.net/my-cloud-function')

print(response.status)

I am getting Unauthorized ( 401 ) error in response. Is this the correct way of invocation?

like image 997
Saras Avatar asked Apr 09 '20 05:04

Saras


People also ask

How do I invoke a cloud function with a service account?

In the New principals field, enter the identity of the calling function. This should be a service account email. Select the role Cloud Functions > Cloud Functions Invoker from the Select a role drop-down menu. Click Save.

Which service account does cloud function use?

At runtime, Cloud Functions defaults to using the App Engine default service account ( [email protected] ), which has the Editor role on the project.


1 Answers

To be able to call your cloud function you need an ID Token against a Cloud Functions end point

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


url = 'https://test-123456.cloudfunctions.net/my-cloud-function'

creds = service_account.IDTokenCredentials.from_service_account_file(
       '/path/to/service-account-credentials.json', target_audience=url)

authed_session = AuthorizedSession(creds)

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

like image 131
Deniss T. Avatar answered Nov 14 '22 21:11

Deniss T.