|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an 'AS IS' BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START functions_bearer_token] |
| 16 | +import requests |
| 17 | + |
| 18 | +# TODO<developer>: set these values |
| 19 | +REGION = 'us-central1' |
| 20 | +PROJECT_ID = 'my-project' |
| 21 | +RECEIVING_FUNCTION = 'my-function' |
| 22 | + |
| 23 | +# Constants for setting up metadata server request |
| 24 | +# See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature |
| 25 | +function_url = f'https://{REGION}-{PROJECT_ID}.cloudfunctions.net/{RECEIVING_FUNCTION}' |
| 26 | +metadata_server_url = \ |
| 27 | + 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=' |
| 28 | +token_full_url = metadata_server_url + function_url |
| 29 | +token_headers = {'Metadata-Flavor': 'Google'} |
| 30 | + |
| 31 | + |
| 32 | +def calling_function(request): |
| 33 | + # Fetch the token |
| 34 | + token_response = requests.get(token_full_url, headers=token_headers) |
| 35 | + jwt = token_response.content |
| 36 | + |
| 37 | + # Provide the token in the request to the receiving function |
| 38 | + function_headers = {'Authorization': f'bearer {jwt}'} |
| 39 | + function_response = requests.get(function_url, headers=function_headers) |
| 40 | + |
| 41 | + return function_response.content |
| 42 | +# [END functions_bearer_token] |
0 commit comments