1. 總覽
在 Cloud Run 建構微服務或多代理應用程式時,內部後端服務不應公開至網際網路。而是將每項後端服務設為需要驗證 (--no-allow-unauthenticated),並僅將 Cloud Run 叫用者 (roles/run.invoker) IAM 角色授予授權呼叫者。
傳統上,如要呼叫已驗證的 Cloud Run 服務,呼叫應用程式必須在程式碼中執行手動權杖插入。在傳送 HTTP 要求之前,您的程式碼會向 Compute 中繼資料伺服器查詢 Google 簽署的 OpenID Connect (OIDC) ID 權杖。該權杖的範圍限定為目的地服務的目標對象網址,而您的程式碼會將其附加至 Authorization: Bearer 標頭。在應用程式程式碼中編寫及維護驗證機制,會造成不必要的阻礙:
- 這會將商業邏輯與 Google Cloud 驗證程式庫結合,降低跨環境的可讀性和可攜性。
- 權杖取得邏輯會因目的地類型和安全性模式而異。舉例來說,Cloud Run 預期會收到 OIDC ID 權杖,Google API 預期會收到 OAuth 2.0 存取權杖,而 mTLS 則需要繫結權杖。
Cloud Run express link (預先發布版) 可讓您不必手動在應用程式程式碼中插入權杖。您在呼叫 (來源) Cloud Run 服務上啟用周邊網路,並建立宣告式 ExpressLink 資源,將來源服務繫結至目的地服務。Google 代管的 Sidecar Proxy 會攔截傳送至目的地的傳出明文 HTTP 要求、自動插入呼叫端服務的身分權杖,並加密與目的地的連線。
在本程式碼實驗室中,您將比較這兩種方法與同一個私人後端服務:
- 部署私人目的地服務和呼叫端服務 (caller-oidc),後者會使用 Python 從 Compute 中繼資料伺服器擷取 OIDC ID 權杖。這個步驟會確認與後端的端對端連線能力,並顯示不使用 express link 時所需的驗證碼。
- 部署第二個呼叫端服務 (caller-express-link),移除中繼資料權杖擷取程式碼,並使用周邊網路和 express link 連結至目的地服務。
PART 1: WITHOUT EXPRESS LINK (caller-oidc) +----------------------------------------------+ +-----------------+ | Caller Service (caller-oidc) | HTTPS | Destination | | | + token | (destination) | | App Container | -------> | | | 1. Parse audience URL with urllib.parse | | Verifies caller | | 2. Fetch OIDC ID token via google-auth | | has IAM role | | 3. Set Authorization: Bearer header | | run.invoker | +----------------------------------------------+ +-----------------+ PART 2: WITH EXPRESS LINK (caller-express-link) +----------------------------------------------+ +-----------------+ | Caller Service (caller-express-link) | HTTPS | Destination | | +----------------+ +----------------+ | + token | (destination) | | | App Container | HTTP | Ambient | | -------> | | | | requests.get() | ---> | Sidecar Proxy | | | Same service | | | (no auth code) | | (Express Link) | | | as Part 1 | | +----------------+ +----------------+ | | (unchanged) | +----------------------------------------------+ +-----------------+
必要條件
- 對 Python 和 HTTP 網路服務有基本瞭解
- 具備 Google Cloud IAM 服務帳戶和 Cloud Run 部署作業的基本知識
課程內容
- 如何部署強制執行 IAM 驗證的私人 Cloud Run 目的地服務
- 如何使用中繼資料伺服器的
google-authOIDC ID 權杖,在 Python 中手動驗證服務對服務要求,以驗證基準連線能力 - 如何移除手動擷取權杖的程式碼,並部署已啟用周邊網路的 Cloud Run 呼叫端服務
- 如何建立 Cloud Run express link,讓呼叫端服務叫用已驗證的目的地服務,完全不需驗證程式碼
建構項目
- destination:Cloud Run 上的私人 Python Flask 服務,會公開
/ping端點 - caller-oidc:Python Flask 服務,會手動擷取 OIDC ID 權杖並插入應用程式程式碼,藉此呼叫 destination
- caller-express-link:並行的 Python Flask 服務,不含權杖插入程式碼,會透過 Express Link 呼叫相同的 destination 服務
軟硬體需求
- 網路瀏覽器,例如 Chrome
- 已啟用計費功能的 Google Cloud 雲端專案,且具備建立 IAM 服務帳戶、Cloud Run 服務和網路服務資源的權限
2. 設定環境
設定 Google Cloud 專案
- 如果沒有 Google 帳戶,請建立帳戶。
- 請改用個人帳戶,而非公司或學校帳戶。公司和學校帳戶可能設有限制,導致您無法啟用本實驗室所需的 API。
- 登入 Google Cloud 控制台。
- 在 Cloud 控制台中啟用計費功能。
- 完成本實驗室所需的 Cloud 資源費用應低於 $1 美元。
- 您可以按照本實驗室結尾的步驟刪除資源,以免產生額外費用。
- 新使用者可享有價值 $300 美元的免費試用期。
- 建立新專案或選擇重複使用現有專案。
- 如果看到專案配額錯誤,請重複使用現有專案,或刪除現有專案來建立新專案。
啟動 Cloud Shell
在本程式碼實驗室中,您將使用 Cloud Shell,這是一個瀏覽器指令列環境,已預先安裝 Google Cloud CLI (gcloud)、Python 和 curl。
- 在 Google Cloud 控制台,點選頂端導覽列中的「啟用 Cloud Shell」。如果出現提示訊息,請點按「授權」。
- 匯出專案 ID 和部署區域,並設定
gcloud以使用$PROJECT_ID。將YOUR_PROJECT_ID替換為專案 ID,並視需要將us-west1替換為其他 Cloud Run 區域:
export PROJECT_ID="YOUR_PROJECT_ID"
export REGION="us-west1"
gcloud config set project "$PROJECT_ID"
- 匯出專案編號和有效的 Google Cloud 帳戶,並確認四個變數都已填入:
export PROJECT_NUMBER=$(gcloud projects describe "$PROJECT_ID" --format="value(projectNumber)")
export ACTIVE_ACCOUNT=$(gcloud config get-value account 2>/dev/null)
echo "PROJECT_ID: $PROJECT_ID | PROJECT_NUMBER: $PROJECT_NUMBER | ACCOUNT: $ACTIVE_ACCOUNT | REGION: $REGION"
更新 gcloud 並啟用 API
- 更新
gcloud元件,取得周邊網路和 Express Link 的最新beta指令:
gcloud components update --quiet
- 啟用 Cloud Run 原始碼部署作業、IAM 服務帳戶、周邊網路和 Network Services Express Link 所需的 Google Cloud API:
gcloud services enable \
iam.googleapis.com \
run.googleapis.com \
cloudbuild.googleapis.com \
artifactregistry.googleapis.com \
networkservices.googleapis.com \
networksecurity.googleapis.com \
trafficdirector.googleapis.com \
cloudtrace.googleapis.com
建立工作區目錄
建立目前使用的目錄,用來存放您在本程式碼實驗室中建構的三個服務資料夾:
mkdir -p ~/express-link-codelab
cd ~/express-link-codelab
3. 部署私人目的地服務
首先,您要部署名為 destination 的私人 Cloud Run 服務。您將在程式碼實驗室的兩個部分重複使用這個單一目的地服務:
- 目的地服務一律不會執行傳出權杖插入作業。
- 目的地服務不需啟用周邊網路,即可透過 Express Link 接收流量。
- 為目的地服務建立專屬 IAM 服務帳戶:
gcloud iam service-accounts create destination-identity \
--display-name="Cloud Run destination service account"
- 建立
destination資料夾並移至該資料夾:
mkdir -p ~/express-link-codelab/destination
cd ~/express-link-codelab/destination
- 執行下列指令,使用 Flask 和 Gunicorn 建立
requirements.txt檔案:
cat << 'EOF' > requirements.txt
Flask==3.0.0
gunicorn==21.2.0
EOF
- 執行下列指令,建立
main.py檔案,公開/ping端點,從K_SERVICE環境變數傳回 Cloud Run 服務名稱:
cat << 'EOF' > main.py
import os
from flask import Flask
app = Flask(__name__)
@app.route("/ping")
def ping():
service_name = os.environ.get("K_SERVICE", "unknown")
return f"Hello from {service_name}"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF
- 使用
--no-allow-unauthenticated從原始碼部署destination,讓 Cloud Run 拒絕未經驗證的要求:
gcloud run deploy destination \
--source . \
--region="$REGION" \
--service-account="destination-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--no-allow-unauthenticated
- 將目的地服務的確定性網址和完整資源 URI 儲存在環境變數中:
export DESTINATION_URL="https://destination-${PROJECT_NUMBER}.${REGION}.run.app"
export DESTINATION_URI="//run.googleapis.com/projects/${PROJECT_NUMBER}/locations/${REGION}/services/destination"
echo "DESTINATION_URL: $DESTINATION_URL"
echo "DESTINATION_URI: $DESTINATION_URI"
- 將
destination的 Cloud Run 叫用者 (roles/run.invoker) 角色授予使用者帳戶,以便直接透過 Cloud Shell 測試:
gcloud run services add-iam-policy-binding destination \
--member="user:$ACTIVE_ACCOUNT" \
--role="roles/run.invoker" \
--region="$REGION"
- 使用自己的身分權杖,將已驗證的要求傳送至
/ping,確認destination正在執行:
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$DESTINATION_URL/ping"
畫面上應會顯示下列回應內容:
Hello from destination
4. 不使用 Express Link 呼叫目的地
在介紹 Express Link 之前,請先建構 caller-oidc,瞭解目前服務對服務驗證的需求,並確認呼叫服務可以連線至 destination。如要在不使用 Express Link 的情況下安全呼叫 destination,您必須設定兩個層級:
- IAM 授權:將
destination的roles/run.invoker角色授予caller-oidc服務帳戶。 - 應用程式層級權杖插入:將
google-auth程式庫新增至caller-oidc,並剖析目標網址,擷取根 OIDC 目標對象。接著,從中繼資料伺服器擷取已簽署的 ID 權杖,並將Authorization: Bearer ID_TOKEN附加至傳出的 HTTPS 要求。
請按照下列步驟設定及部署 caller-oidc:
- 為
caller-oidc建立專屬服務帳戶:
gcloud iam service-accounts create caller-oidc-identity \
--display-name="Cloud Run OIDC caller service account"
- 授權
caller-oidc-identity叫用destination:
gcloud run services add-iam-policy-binding destination \
--member="serviceAccount:caller-oidc-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/run.invoker" \
--region="$REGION"
- 在
destination旁建立caller-oidc目錄:
mkdir -p ~/express-link-codelab/caller-oidc
cd ~/express-link-codelab/caller-oidc
- 執行下列指令,建立
requirements.txt檔案。請注意,您必須特別新增google-auth,才能在應用程式容器中處理權杖擷取作業:
cat << 'EOF' > requirements.txt
Flask==3.0.0
google-auth==2.23.0
requests==2.31.0
gunicorn==21.2.0
EOF
- 執行下列指令,建立手動插入 OIDC 權杖的
main.py檔案:
cat << 'EOF' > main.py
import os
from urllib.parse import urlparse
from flask import Flask, request
from google.auth.transport.requests import Request as GoogleAuthRequest
from google.oauth2 import id_token
import requests
app = Flask(__name__)
@app.route("/ping")
def ping():
service_name = os.environ.get("K_SERVICE", "unknown")
return f"Hello from {service_name}"
@app.route("/")
def call_destination():
target_url = request.args.get("target_url")
if not target_url:
return "Error: target_url query parameter not set.", 400
try:
# 1. Extract the root service URL (scheme + host) for the OIDC audience claim
parsed_url = urlparse(target_url)
target_audience = f"{parsed_url.scheme}://{parsed_url.netloc}"
# 2. Fetch a Google-signed OIDC ID token from the metadata server
auth_req = GoogleAuthRequest()
token = id_token.fetch_id_token(auth_req, target_audience)
# 3. Inject the token as an HTTP Bearer header
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(target_url, headers=headers, timeout=10)
return f"I called the destination and it replied: '{response.text}'"
except Exception as e:
return f"Error calling destination: {str(e)}", 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF
- 將
caller-oidc部署至 Cloud Run:
gcloud run deploy caller-oidc \
--source . \
--region="$REGION" \
--service-account="caller-oidc-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--no-allow-unauthenticated
- 授予使用者帳戶叫用
caller-oidc的權限:
gcloud run services add-iam-policy-binding caller-oidc \
--member="user:$ACTIVE_ACCOUNT" \
--role="roles/run.invoker" \
--region="$REGION"
- 儲存
caller-oidc的確定性網址並叫用,將 HTTPS 網址$DESTINATION_URL/ping傳遞為target_url:
export CALLER_OIDC_URL="https://caller-oidc-${PROJECT_NUMBER}.${REGION}.run.app"
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$CALLER_OIDC_URL/?target_url=$DESTINATION_URL/ping"
您應該會收到 destination 的成功回覆:
I called the destination and it replied: 'Hello from destination'
5. 部署 Express Link 的呼叫端服務
接著,您要在同層目錄中建構第二個呼叫端服務 caller-express-link。有了 express link,caller-express-link 完全不需要權杖插入程式碼,可直接呼叫 requests.get(target_url, timeout=10)。
- 為
caller-express-link建立專屬服務帳戶:
gcloud iam service-accounts create caller-express-link-identity \
--display-name="Cloud Run Express Link caller service account"
- 將
roles/trafficdirector.client角色授予caller-express-link-identity,讓代管的周邊網路 sidecar 下載 Express Link 轉送和安全性設定。另外,請授予roles/cloudtrace.agent,讓 sidecar 能夠匯出追蹤記錄 span:
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/trafficdirector.client"
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/cloudtrace.agent"
- 在
caller-oidc旁建立caller-express-link目錄:
mkdir -p ~/express-link-codelab/caller-express-link
cd ~/express-link-codelab/caller-express-link
- 執行下列指令,建立不含
google-auth的requirements.txt檔案:
cat << 'EOF' > requirements.txt
Flask==3.0.0
requests==2.31.0
gunicorn==21.2.0
EOF
- 執行下列指令,建立
main.py檔案,其中包含一般requests.get(target_url, timeout=10)呼叫,且不含權杖插入邏輯:
cat << 'EOF' > main.py
import os
from flask import Flask, request
import requests
app = Flask(__name__)
@app.route("/ping")
def ping():
service_name = os.environ.get("K_SERVICE", "unknown")
return f"Hello from {service_name}"
@app.route("/")
def call_destination():
target_url = request.args.get("target_url")
if not target_url:
return "Error: target_url query parameter not set.", 400
try:
response = requests.get(target_url, timeout=10)
return f"I called the destination and it replied: '{response.text}'"
except Exception as e:
return f"Error calling destination: {str(e)}", 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF
- 對
../caller-oidc/main.py執行diff,查看您移除的驗證樣板:
diff -u ../caller-oidc/main.py main.py || true
- 使用
gcloud beta run deploy部署caller-express-link,並啟用--ambient-networking和--ambient-scope=global:
gcloud beta run deploy caller-express-link \
--source . \
--region="$REGION" \
--service-account="caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--no-allow-unauthenticated \
--ambient-networking \
--ambient-scope=global
- 確認
caller-express-link已啟用周邊網路:
gcloud run services describe caller-express-link --region="$REGION"
在修訂版本摘要結尾,確認是否顯示 Ambient Networking 和 Ambient Scope:
Ambient Networking: Enabled Ambient Scope: global
- 授予使用者帳戶叫用
caller-express-link的權限,並授權caller-express-link-identity叫用destination:
gcloud run services add-iam-policy-binding caller-express-link \
--member="user:$ACTIVE_ACCOUNT" \
--role="roles/run.invoker" \
--region="$REGION"
gcloud run services add-iam-policy-binding destination \
--member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/run.invoker" \
--region="$REGION"
- 儲存
caller-express-link的網址和資源 URI,以及destination的 HTTP (http://) 確定性網址:
export CALLER_EL_URL="https://caller-express-link-${PROJECT_NUMBER}.${REGION}.run.app"
export CALLER_EL_URI="//run.googleapis.com/projects/${PROJECT_NUMBER}/locations/${REGION}/services/caller-express-link"
export DESTINATION_HTTP_URL="http://destination-${PROJECT_NUMBER}.${REGION}.run.app"
echo "CALLER_EL_URL: $CALLER_EL_URL"
echo "CALLER_EL_URI: $CALLER_EL_URI"
echo "DESTINATION_HTTP_URL: $DESTINATION_HTTP_URL"
- 先測試透過
caller-express-link呼叫destination,再建立 Express Link:
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$CALLER_EL_URL/?target_url=$DESTINATION_HTTP_URL/ping"
如預期,呼叫失敗並顯示 403 Forbidden,因為尚未有 Express Link 攔截要求並插入憑證:
I called the destination and it replied: ' <html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>403 Forbidden</title> </head> <body text=#000000 bgcolor=#ffffff> <h1>Error: Forbidden</h1> <h2>Your client does not have permission to get URL <code>/ping</code> from this server.</h2> <h2></h2> </body></html> '
6. 使用 Express Link 連結服務
現在,您要宣告 ExpressLink 資源,將 caller-express-link (來源服務) 連結至 destination,完全不必變更任何程式碼,也不必重新部署 Cloud Run 服務。
- 在
global位置建立 Express Link 資源:
gcloud beta network-services express-links create caller-to-destination \
--location=global \
--description="Express Link from caller-express-link to destination" \
--source-services="$CALLER_EL_URI" \
--destination-services="$DESTINATION_URI"
- 列出 express link,確認資源是否存在:
gcloud beta network-services express-links list --location=global
指令輸出:
NAME caller-to-destination
- 檢查 Express Link 設定詳細資料:
gcloud beta network-services express-links describe caller-to-destination --location=global
指令輸出:
createTime: '2026-10-27T19:30:04.492105068Z' description: Express Link from caller-express-link to destination destination: services: - //run.googleapis.com/projects/PROJECT_NUMBER/locations/us-west1/services/destination etag: ... name: projects/PROJECT_ID/locations/global/expressLinks/caller-to-destination source: services: - //run.googleapis.com/projects/PROJECT_NUMBER/locations/us-west1/services/caller-express-link updateTime: '2026-10-27T19:30:11.309054865Z'
- 對
caller-express-link重新執行完全相同的curl要求:
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$CALLER_EL_URL/?target_url=$DESTINATION_HTTP_URL/ping"
這次,Ambient sidecar 會攔截傳送至 destination 的 HTTP 要求、插入 caller-express-link-identity 的身分權杖、將連線升級至 TLS,並傳回目的地的回應:
I called the destination and it replied: 'Hello from destination'
比較手動權杖插入與 Express Link
下表摘要說明 caller-oidc 和 caller-express-link 之間的差異:
維度 | 不使用 Express Link ( | 使用 Express Link ( |
| 需要「 | 無 (僅限 |
| 剖析目標對象網址、呼叫 | 純文字 |
應用程式中的目標網址配置 |
|
|
呼叫端 Cloud Run 設定 | 標準部署項目 |
|
目的地 Cloud Run 設定 |
| 不變 ( |
7. 清除
為避免系統持續向您的 Google Cloud 帳戶收取費用,請刪除您在本程式碼實驗室中建立的資源。
- 刪除 Express Link 資源:
gcloud beta network-services express-links delete caller-to-destination --location=global --quiet
- 刪除三個 Cloud Run 服務:
gcloud run services delete caller-express-link --region="$REGION" --quiet
gcloud run services delete caller-oidc --region="$REGION" --quiet
gcloud run services delete destination --region="$REGION" --quiet
- 移除專案層級的身分與存取權管理政策繫結,並刪除三個服務帳戶:
gcloud projects remove-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/trafficdirector.client" \
--quiet
gcloud projects remove-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/cloudtrace.agent" \
--quiet
gcloud iam service-accounts delete "caller-express-link-identity@${PROJECT_ID}.iam.gserviceaccount.com" --quiet
gcloud iam service-accounts delete "caller-oidc-identity@${PROJECT_ID}.iam.gserviceaccount.com" --quiet
gcloud iam service-accounts delete "destination-identity@${PROJECT_ID}.iam.gserviceaccount.com" --quiet
- (選用) 如果您專為這個程式碼實驗室建立 Google Cloud 專案,可以刪除整個專案:
# Run only if you want to delete the entire project and all its resources
gcloud projects delete "$PROJECT_ID"
8. 恭喜
您已部署私人 Cloud Run 後端服務,並使用 Python 手動插入 OIDC 權杖來呼叫該服務。接著,您將所有應用程式層級的驗證程式碼,替換為宣告式 Cloud Run express link。
您學到的內容
- 為何手動插入 OIDC 權杖會將應用程式商業邏輯與平台驗證程式庫和安全性模式結合
- 如何部署經過驗證的 Cloud Run 目的地服務,無論是否使用 express link,都能正常運作
- 如何啟用周邊網路 (
--ambient-networking搭配--ambient-scope=global),並在呼叫 Cloud Run 服務時授予 Traffic Director 用戶端權限 (roles/trafficdirector.client) - 如何建立及檢查 Network Services
ExpressLink資源,自動插入身分權杖,並將容器的明文http://呼叫升級為加密 TLS 連線
後續步驟
- 參閱 Cloud Run 說明文件中的「服務對服務驗證」一文。
- 查看 Cloud Run 版本資訊,瞭解周邊網路和 Express Link 的最新消息。