From Documentation:
Receiving Function
First, you'll need to configure the receiving function to accept requests from the calling function:
Grant the Cloud Functions Invoker (roles/cloudfunctions.invoker) role to the calling function identity on the receiving function. By default, this identity is [email protected]
Use the gcloud functions add-iam-policy-binding command:
gcloud functions add-iam-policy-binding RECEIVING_FUNCTION \
--member='serviceAccount:CALLING_FUNCTION_IDENTITY' \
--role='roles/cloudfunctions.invoker'
where RECEIVING_FUNCTION is the receiving function, and CALLING_FUNCTION_IDENTITY is the calling function identity.
Calling Function
In the calling function, you'll need to:
- Create a Google-signed OAuth ID token with the audience (aud) set to the URL of the receiving function.
- Include the ID token in an Authorization: Bearer ID_TOKEN header in the request to the function.
# Requests is already installed, no need to add it to requirements.txt
import requests
def calling_function(request):
# Make sure to replace variables with appropriate values
receiving_function_url = 'https://REGION-PROJECT.cloudfunctions.net/RECEIVING_FUNCTION'
# Set up metadata server request
# See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
metadata_server_token_url = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience='
token_request_url = metadata_server_token_url + receiving_function_url
token_request_headers = {'Metadata-Flavor': 'Google'}
# Fetch the token
token_response = requests.get(token_request_url, headers=token_request_headers)
jwt = token_response.content.decode("utf-8")
# Provide the token in the request to the receiving function
receiving_function_headers = {'Authorization': f'bearer {jwt}'}
function_response = requests.get(receiving_function_url, headers=receiving_function_headers)
return function_response.content
More info can be found here