Search code examples
pythongoogle-cloud-platformgoogle-cloud-functionsservice-accountshttp-authentication

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?


Solution

  • 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)