我在从云函数发送经过验证的防火墙REST请求时遇到了问题。请求需要在头中有一个oauth2令牌。我在这里跟踪了文档https://cloud.google.com/functions/docs/securing/authenticating,并尝试了它们提供的python函数,但这仍然不能提供正确的身份验证。到目前为止,已经成功的是从gcloud auth application-default print-access-token
复制令牌,但在一个小时后就过期了。有什么想法吗?
import urllib
import google.auth.transport.requests
import google.oauth2.id_token
def make_authorized_get_request(endpoint, audience):
"""
make_authorized_get_request makes a GET request to the specified HTTP endpoint
by authenticating with the ID token obtained from the google-auth client library
using the specified audience value.
"""
# Cloud Functions uses your function's URL as the `audience` value
# audience = https://project-region-projectid.cloudfunctions.net/myFunction
# For Cloud Functions, `endpoint` and `audience` should be equal
req = urllib.request.Request(endpoint)
auth_req = google.auth.transport.requests.Request()
id_token = google.oauth2.id_token.fetch_id_token(auth_req, audience)
req.add_header("Authorization", f"Bearer {id_token}")
response = urllib.request.urlopen(req)
return response.read()
上面的函数导致一个urllib.error.HTTPError: HTTP Error 401: Unauthorized"
发布于 2022-10-28 07:30:42
在我的例子中,解决方案是将datastore.importExportAdmin "Cloud“角色添加到将生成令牌的服务帐户中。并使用下面的代码从凭据中生成令牌:
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
https://stackoverflow.com/questions/74229968
复制相似问题