使用輸出和輸入設定限制服務存取權

您可以只允許相同 Google Cloud 專案或 VPC Service Controls 服務範圍內的資源 (例如 Cloud Run) 呼叫 Cloud Functions,確保 Cloud Functions 的安全。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:

程式碼範例

Python

如要向 Cloud Run 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import os
import urllib

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


def get_hello_world(request):
    try:
        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)
        return response.read()

    except Exception as e:
        print(e)
        return str(e)

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器