Using egress and ingress settings to restrict access to services

Secure your Cloud Functions by allowing them to be called only by resources, like Cloud Run, in the same Google Cloud project or VPC Service Controls service perimeter.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import os
import urllib

import google.auth.transport.requests
import google.oauth2.id_token

def get_hello_world(request):
        url = os.environ.get("URL")
        req = urllib.request.Request(url)

        auth_req = google.auth.transport.requests.Request()
        id_token = google.oauth2.id_token.fetch_id_token(auth_req, url)
        req.add_header("Authorization", f"Bearer {id_token}")

        response = urllib.request.urlopen(req)

    except Exception as e:
        return str(e)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.