【问题标题】:Google Cloud How to get authorization?谷歌云如何获得授权?
【发布时间】:2020-02-29 19:46:48
【问题描述】:

我需要获取我的 Google 云项目的实例列表。所以我尝试了这个:

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

如何在 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"
  }
}

如何为我的 Google Cloud 项目获取“OAuth 2 访问令牌”

【问题讨论】:

    标签: python gcloud


    【解决方案1】:

    这里是full documentation on Server to Server authentication,其中还包括支持的每种方法的示例代码。

    在此GCP Github code 中,您可以看到多种身份验证方式,您可以根据自己的用例选择这些方式。

    例如,通过此代码示例,您可以使用服务帐户 JSON 密钥进行身份验证:

    # [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]
    

    更新: 如果您想要的只是获取 Bearer 令牌并将其存储在 python 变量中以发出简单的 GET 请求:

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

    因此 your_key 现在将拥有您需要包含在请求标头中的 Bearer 令牌

    否则,请通读this documentation,其中解释了如何以最终用户身份进行身份验证。

    【讨论】:

    • 对不起,我觉得你比我高几个级别。所以我什么都不懂。我需要在 Python 中为我的 Get 请求获取 OAuth2 身份验证。
    • 用您可能提到的更多选项更新了我的答案。如果这不是您想要的,请使用确切的用例和不适合您的内容编辑您的问题。 @DerPazi
    【解决方案2】:

    我建议您使用 Google 的 API 客户端库。

    Google 的库(几乎每个服务都有一个)不仅为 Compute Engine 提供 Python SDK,而且还实现了身份验证和日志记录等。

    https://cloud.google.com/compute/docs/tutorials/python-guide

    如果您确实需要直接调用 API,则需要提供不记名令牌:

    TOKEN="$(gcloud auth print-access-token)"
    curl --header "Authorization: Bearer ${TOKEN}" https://...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      相关资源
      最近更新 更多