DerPazi
DerPazi

Reputation: 13

Google Cloud How to get authorization?

I need to get the Instance List of my Google cloud project. So i tried this:

requests.get('https://compute.googleapis.com/compute/v1/projects/clouddeployment-265711/zones/europe-west3-a/instances)

How do i get authorization in python?.

{
  "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"
  }
}

How do i get my "OAuth 2 access token" for my Google Cloud Project

Upvotes: 1

Views: 1436

Answers (1)

Waelmas
Waelmas

Reputation: 1962

Here is the full documentation on Server to Server authentication which also includes sample codes for every method supported.

In this GCP Github code, you can see multiple ways of authentication that you might choose from depending on your use-case.

For example with this code sample you can use a service account JSON key for authentication:

# [START auth_api_explicit]
def explicit(project):
    from google.oauth2 import service_account
    import googleapiclient.discovery

    # Construct service account credentials using the service account key
    # file.
    credentials = service_account.Credentials.from_service_account_file(
        'service_account.json')

    # Explicitly pass the credentials to the client library.
    storage_client = googleapiclient.discovery.build(
        'storage', 'v1', credentials=credentials)

    # Make an authenticated API request
    buckets = storage_client.buckets().list(project=project).execute()
    print(buckets)
# [END auth_api_explicit]

UPDATE: If what you want is simply getting the Bearer token and storing it in a python variable to make a simple GET request:

import os

your_key = os.system('gcloud auth print-access-token')

so your_key will now have the Bearer token that you need to include in your request header

Otherwise, please read through this documentation which explains how to authenticate as an end-user.

Upvotes: 1

Related Questions