Cloud Function调用Dataform REST API时身份令牌认证失败
问题原因
你使用google.oauth2.id_token.fetch_id_token()生成的是ID Token,但Dataform REST API要求的是OAuth 2.0 Access Token,这就是认证失败的核心原因。ID Token用于身份校验,而Access Token才是Google Cloud API认可的授权凭证。
解决方案
改用google.auth库获取默认服务账号的Access Token,替换原有的ID Token生成逻辑:
import requests import google.auth import google.auth.transport.requests def get_workflow_invocation_actions(environment, git_repo, workflow_invocation_id): parent = f"projects/{environment}/locations/europe-west2/repositories/{git_repo}" name = f"{parent}/workflowInvocations/{workflow_invocation_id}" # The API endpoint url = f"https://dataform.googleapis.com/v1beta1/{name}:query" # 获取默认凭据(Cloud Function运行时自动关联服务账号) credentials, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) # 刷新凭据获取Access Token auth_req = google.auth.transport.requests.Request() credentials.refresh(auth_req) # 用Access Token发起请求 response = requests.get(url, headers={'Authorization': f'Bearer {credentials.token}'}) # Print the response print(response.json())
额外验证点
- 确认Cloud Function使用的服务账号已被授予
dataform.workflowInvocations.query权限,权限可能需要几分钟时间完成全局同步。 - 确保代码中的
environment参数是正确的项目ID,而非项目名称。
内容的提问来源于stack exchange,提问作者RoyalSwish
相关产品推荐
相关产品推荐

