Google Cloud静态IP创建异常:命令返回成功但访问报401未授权
问题详情
在Google Cloud控制台终端执行以下命令创建静态IP地址:
gcloud compute addresses create helloweb-ip --region us-central1
命令返回创建成功的信息:
Created [https://www.googleapis.com/compute/v1/projects/<project-name>-409407/regions/us-central1/addresses/helloweb-ip]
但直接在浏览器中访问该链接时,返回401未授权的JSON错误:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadatas": { "service": "compute.googleapis.com", "method": "compute.v1.RegionAddressesService.Get" } } ] } }
已确认处于登录状态的Cloud Console,且命令直接在控制台终端执行,仍无法解决该问题。
原因解释
返回的链接是Google Compute Engine的REST API端点,直接通过浏览器访问时,不会自动携带GCP的认证凭证(如OAuth 2.0访问令牌)。即使你已登录Cloud Console,浏览器的会话凭证和API所需的认证令牌是分离的,因此会触发401未授权错误。
正确查看静态IP的方式
通过GCP控制台界面查看:
进入「VPC网络」->「外部IP地址」页面,即可找到名为helloweb-ip的静态IP地址及其详细信息。通过gcloud命令查看:
在控制台终端执行以下命令,直接获取该静态IP的详细配置:gcloud compute addresses describe helloweb-ip --region us-central1通过API访问(需携带认证令牌):
如果需要通过API端点访问,需先获取有效的访问令牌,再通过curl等工具发起请求:- 在控制台终端获取访问令牌:
gcloud auth print-access-token - 携带令牌发起API请求:
curl -H "Authorization: Bearer $(gcloud auth print-access-token)" https://www.googleapis.com/compute/v1/projects/<project-name>-409407/regions/us-central1/addresses/helloweb-ip
- 在控制台终端获取访问令牌:
内容的提问来源于stack exchange,提问作者Kirk Sefchik
相关产品推荐
相关产品推荐

