打开我的 Google Cloud 运行 服务的 URL 时出现 401 未授权错误

401 unauthorized error when opening the URL of my Google Cloud Run service

我构建了一个示例容器(Go 示例,https://cloud.google.com/run/docs/quickstarts/build-and-deploy)并部署到云端 运行(我未选中 "allow unauthenticated invocations")。

但是,当我打开服务的端点 URL 时,我得到一个 401 页面,

<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>401 Unauthorized</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Unauthorized</h1>
<h2>Your client does not have permission to the requested URL <code>/</code>.</h2>
<h2></h2>
</body></html>
curl -H "Authorization: Bearer $(gcloud config config-helper --format 'value(credential.id_token)')" [SERVICE_URL]

有什么可以打开端点的吗?

  1. 请确保 gcloud 版本至少为 243.0.0 by "gcloud --version"

  2. 如果gcloud太旧请用"gcloud components update"更新

  3. [已更新] 在 Cloud Shell 中使用 gcloud 调用需要身份验证的 Cloud 运行 服务现在也可以正常工作。

谢谢!

我设法从云功能连接,最后,在调用不允许未经身份验证的调用的云 运行 服务时遇到相同的 401 错误 15 分钟后:

import google.auth

auth_req = google.auth.transport.requests.Request()
id_token = google.oauth2.id_token.fetch_id_token(auth_req, URL)

headers = {'Authorization': 'Bearer ' + id_token,
               "Content-Type": "application/json; charset=utf-8"}
response = requests.post(URL, json=request_json, headers=headers)