2015-12-09 85 views
1

我在我的項目中創建了許多vm,我想從中查詢gcloud終端的api。 我正在嘗試查詢任何API,即使我已被授權/登錄到gcloud終端,但獲取401 - 「需要登錄」錯誤。Google Compute Engine:無法從gcloud終端查詢API

C:\..\Google\Cloud SDK>gcloud config list 
[core] 
account = [email protected]*****.com 
disable_usage_reporting = True 
project = <proj-id> 
[meta] 
active_config = default 

C:\..\Google\Cloud SDK>curl https://www.googleapis.com/compute/v1/projects/<proj-id>/aggregated/disks 
{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "required", 
    "message": "Login Required", 
    "locationType": "header", 
    "location": "Authorization" 
    } 
    ], 
    "code": 401, 
    "message": "Login Required" 
} 
} 

回答

1

由於錯誤中提到:

"message": "Login Required", 
"locationType": "header", 
"location": "Authorization" 

因爲你正在做一個HTTP API調用Google API的,你需要把OAuth訪問令牌在header of your HTTP request

GET compute/v1/projects/<proj-id>/aggregated/disks HTTP/1.1 
Host: www.googleapis.com 
Authorization: Bearer XXXXXXXXXXXXXXXXXXX 

有幾種方法可以獲得OAuth訪問令牌。一個簡單的方法是通過谷歌的oauthplayground

  1. 選擇您所需的API範圍
  2. 點擊授權的API按鈕
  3. 點擊「爲令牌兌換授權碼」
  4. 你將有你的訪問令牌的捲曲請求頭使用它
1

您需要攜帶授權令牌使用REST API時:

gcloud auth login

TOKEN=$(gcloud auth print-access-token)

curl -H "Authorization: Bearer $TOKEN" <url>

相關問題