【问题标题】:AppAssertionCredentials fail with 401AppAssertionCredentials 失败并出现 401
【发布时间】:2015-02-16 20:19:58
【问题描述】:

按照此处的说明进行操作: https://developers.google.com/accounts/docs/OAuth2ServiceAccount?hl=en_US

我尝试在我的谷歌计算引擎实例上运行这个 python 脚本:

import httplib2
from googleapiclient.discovery import build
from oauth2client.gce import AppAssertionCredentials

credentials = AppAssertionCredentials("https://www.googleapis.com/auth/datastore")
http = credentials.authorize(httplib2.Http())
service = build('datastore', 'v1beta2', http=http)
x = service.datasets().lookup(body='', datasetId='surferjeff-easybates').execute(http=http)

但我仍然收到此错误:

Traceback (most recent call last):
  File "C:/Users/surferjeff-easybates/Desktop/test.py", line 8, in <module>
    x = service.datasets().lookup(body='', datasetId='surferjeff-easybates').execute(http=http)
  File "C:\Python27\lib\site-packages\oauth2client\util.py", line 135, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Python27\lib\site-packages\googleapiclient\http.py", line 723, in execute
    raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 401 when requesting https://www.googleapis.com/datastore/v1beta2/datasets/surferjeff-easybates/lookup?alt=json returned "Invalid Credentials">

我已验证我的帐户已启用数据存储。我做错了什么?

【问题讨论】:

    标签: python google-api google-authentication google-api-python-client


    【解决方案1】:

    问题与 Google 的一个简单错误有关。

    当您使用云控制台创建一个新实例并选中“允许 API 访问同一项目中的所有 Google Cloud 服务” 时,您将此实例包含在所有可能的云范围中.

    当您尝试查看哪个 REST 请求生成了这个强大的功能时(通过按“等效 REST 或命令行”按钮),您会看到该实例是使用一个全局范围生成的,如下所示:

      "scopes": [
        "https://www.googleapis.com/auth/cloud-platform"
      ]
    

    如果您尝试使用具有相同范围的 Google API 客户端 (apiclient) 创建此实例,您会发现它无法获取有效凭据以使用 Datastore 服务。

    解决方案在于,当您通过控制台创建实例时,单个范围显然不是 Google 分配给您的实例的范围。

    如果在创建实例后打开实例详情,会发现它有以下作用域:

      "scopes": [
        "https://www.googleapis.com/auth/cloud-platform",
        "https://www.googleapis.com/auth/datastore",
        "https://www.googleapis.com/auth/userinfo.email"
      ]
    

    一旦您明确提及数据存储的范围,一切都会按预期进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      相关资源
      最近更新 更多