1. 概览
在 Cloud Run 上构建微服务或多智能体应用时,内部后端服务不应向公共互联网开放。而是将每个后端服务配置为需要身份验证 (--no-allow-unauthenticated),并仅向获得授权的调用方授予 Cloud Run Invoker (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 服务上启用 Ambient Networking,并创建一个声明式 ExpressLink 资源,用于将源服务绑定到目标服务。Google 代管的边车代理会拦截发往目标位置的出站明文 HTTP 请求,自动注入调用方服务的身份令牌,并加密与目标位置的连接。
在此 Codelab 中,您将针对同一私有后端服务比较这两种方法:
- 部署一个专用目标服务和一个调用方服务 (caller-oidc),后者使用 Python 从计算元数据服务器提取 OIDC ID 令牌。此步骤可确认与后端的端到端连接性,并显示在不使用 Express Link 的情况下所需的身份验证码。
- 部署第二个调用方服务 (caller-express-link),移除元数据令牌提取代码,并使用 Ambient Networking 和 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 Web 服务
- 基本熟悉 Google Cloud IAM 服务账号和 Cloud Run 部署
学习内容
- 如何部署强制执行 IAM 身份验证的专用 Cloud Run 目标服务
- 如何使用 Python 手动对服务到服务请求进行身份验证,方法是使用来自元数据服务器的
google-authOIDC ID 令牌来验证基准连接 - 如何移除手动令牌提取代码,并部署启用了 Ambient Networking 的 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
- 一个已启用结算功能且有权创建 IAM 服务账号、Cloud Run 服务和网络服务资源的 Google Cloud 项目
2. 设置您的环境
设置 Google Cloud 项目
- 如果您还没有 Google 账号,则必须创建一个 Google 账号。
- 使用个人账号,而非工作或学校账号。工作账号和学校账号可能存在限制,导致您无法启用本实验所需的 API。
- 登录 Google Cloud 控制台。
- 在 Cloud 控制台中启用结算功能。
- 完成本实验所需的 Cloud 资源费用应低于 1 美元。
- 您可以按照本实验末尾的步骤删除资源,以免产生更多费用。
- 新用户符合参与 $300 USD 免费试用计划的条件。
- 创建新项目或选择重复使用现有项目。
- 如果您看到有关项目配额的错误,请重复使用现有项目或删除现有项目以创建新项目。
启动 Cloud Shell
在此 Codelab 中,您将使用 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组件,以便获取适用于 Ambient Networking 和 Express Link 的最新beta命令:
gcloud components update --quiet
- 启用 Cloud Run 源代码部署、IAM 服务账号、Ambient Networking 和 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
创建工作区目录
创建一个工作目录,用于存放您将在本 Codelab 中构建的三个服务文件夹:
mkdir -p ~/express-link-codelab
cd ~/express-link-codelab
3. 部署专用目标服务
首先,您将部署一个名为 destination 的私有 Cloud Run 服务。您将在本 Codelab 的两个部分中重复使用此单一目标服务:
- 目标服务绝不会执行出站令牌注入。
- 目标服务无需启用 Ambient Networking 即可通过 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 Invoker (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 授权:向
caller-oidc服务账号授予destination的roles/run.invoker角色。 - 应用级令牌注入:将
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"
- 向
caller-express-link-identity授予roles/trafficdirector.client角色,以便代管式 Ambient Networking 边车可以下载 Express Link 路由和安全配置。此外,还需授予roles/cloudtrace.agent,以便边车可以导出跟踪 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
- 运行以下命令,创建一个包含普通
requests.get(target_url, timeout=10)调用且不含令牌注入逻辑的main.py文件:
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上是否已启用 Ambient Networking:
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"
- 在创建 Express Link 之前,请先测试通过
caller-express-link调用destination:
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 边车会拦截对 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 账号持续收取费用,请删除您在此 Codelab 期间创建的资源。
- 删除 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
- 移除项目级 IAM 政策绑定,并删除这三个服务账号:
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
- (可选)如果您专门为此 Codelab 创建了一个 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 都能正常运行
- 如何在调用方 Cloud Run 服务上启用 Ambient Networking(
--ambient-networking与--ambient-scope=global)并授予 Traffic Director 客户端权限 (roles/trafficdirector.client) - 如何创建和检查 Network Services
ExpressLink资源,该资源会自动注入身份令牌,并将容器中的明文http://调用升级为加密 TLS 连接
后续步骤
- 阅读 Cloud Run 文档中的对服务到服务进行身份验证。
- 如需了解 Ambient Networking 和 Express Link 的最新动态,请查看 Cloud Run 版本说明。