1
votes

I have many vm's created inside my project, from which I want to query api's from gcloud terminal. I am getting 401 - "Login Required" error while I am trying to query any API, even though I am authorized/logged-in to gcloud terminal.

C:\..\Google\Cloud SDK>gcloud config list
[core]
account = remis.haroon@*****.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"
 }
}
2

2 Answers

2
votes

You need to carry authorization token when using the REST API:

gcloud auth login

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

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

1
votes

As the error mentions:

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

Since you are doing an HTTP API call to google apis, you need to put the OAuth access token in the header of your HTTP request.

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

There are several ways to obtain the OAuth access token. One easy way is through google's oauthplayground.

  1. Choose your required API scopes
  2. Click on Authorize APIs button
  3. Click on "Exchange authorization code for tokens"
  4. You will have your access token to use it in the curl request header