【发布时间】:2021-04-15 18:09:36
【问题描述】:
我正在尝试生成一个 id_token 以使用我从here 获得的以下代码对 Google Cloud Functions 进行经过身份验证的调用:
# IAP audience is the ClientID of IAP-App-Engine-app in
# the API->credentials page
# Cloud Function and Cloud Run need the base URL of the service
audience = 'my_cloud_function_url'
# #1 Get the default credential to generate the access token
credentials, project_id = google.auth.default()
# #2 To use the current service account email
service_account_email = credentials.service_account_email
# Don't work with user account, so define manually the email
# service_account_email = 'MY SERVICE ACCOUNT EMAIL'
# #3 prepare the call the the service account credentials API
sa_credentials_url = f'https://iamcredentials.googleapis.com/' \
f'v1/projects/-/serviceAccounts/' \
f'{service_account_email}:generateIdToken'
headers = {'Content-Type': 'application/json'}
# Create an AuthorizedSession that includes
# automatically the access_token based on your credentials
authed_session = AuthorizedSession(credentials)
# Define the audience in the request body
# add the parameter "'includeEmail':true" for IAP access
body = json.dumps({'audience': audience})
# Make the call
token_response = authed_session.request('POST',sa_credentials_url,
data=body, headers=headers)
jwt = token_response.json()
id_token = jwt['token']
我没有在 Google Cloud 环境中运行它,因此我将我的 GOOGLE_APPLICATION_CREDENTIALS 设置为来自我在控制台中生成的服务帐户的 json 文件。我要求我的网络管理员在 ['https://www.googleapis.com/auth/cloud-platform'] 范围内授权服务帐户。
当我运行脚本时,我收到以下错误:
{'error': {'code': 403, 'message': 'The caller does not have permission', 'status': 'PERMISSION_DENIED'}}
我认为此错误与此服务帐户没有某些实习生访问权限有关,但我不确定,有人可以帮我解决这个问题吗?
编辑:
正如@guillaume blaquiere 在 cmets 上所说,您可以在不调用服务帐户凭据 API 的情况下获取 id_token,我可以获得 id_token,但无法使用该 id_token 调用我的服务帐户
import google.oauth2.id_token
import google.auth.transport.requests
request = google.auth.transport.requests.Request()
audience = 'my_cloud_function_url'
id_token = google.oauth2.id_token.fetch_id_token(request, audience)
headers = {'Authorization': f'bearer {id_token}'}
service_response = requests.get(audience, headers=headers)
有谁知道为什么 id_token 无效?
【问题讨论】:
标签: python google-cloud-functions google-authentication service-accounts