【问题标题】:Is API Key enough to access GAE AdminAPI features?API Key 是否足以访问 GAE AdminAPI 功能?
【发布时间】:2021-05-16 15:56:22
【问题描述】:

我正在尝试为我的 Python 3 Google App Engine 自动创建防火墙规则。 Per their docs,我可以为此使用 Admin API(我已在 Cloud Console 中启用)。我也在the APIs & Keys/Credentials page 上创建了一个API Key(没有限制)。 Python library 表示我可以将此密钥与该库一起使用。但是,当我将API_KEY 与以下代码一起使用时,我得到:

googleapiclient.errors.HttpError: <HttpError 401 when requesting https://appengine.googleapis.com/v1beta/apps/{my project ID}/firewall/ingressRules?key={my API Key}&alt=json returned "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.". Details: "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.">

错误中的 URL 没有用,因为我故意尝试 not 使用 Oauth2(矫枉过正)。这是产生上述错误的代码:

from googleapiclient.discovery import build


def set_firewall_rules(file_name):
    infile = open(file_name)
    service = build('appengine', 'v1beta', developerKey=API_KEY)
    existing_rules = service.apps().firewall().ingressRules().list(appsId='{my project ID')
    print(existing_rules.execute())
    service.close()
    return

为什么我的 API 密钥不足?我的应用是否有需要更改的设置,或者我是否必须创建一个包含范围和所有 Oauth2 内容的服务帐户?

另外,我注意到如果我将service.close() 行移到print 行之前,我会得到AttributeError: 'Http' object has no attribute 'http',所以看来我离成功至少还有两步之遥。它使在 bash 脚本中使用 gcloud 变得更简单...

我在带有 google-api-python-client 1.12.8 的虚拟环境中使用 Python 3.8。

【问题讨论】:

    标签: python google-app-engine google-api python-3.8


    【解决方案1】:

    很遗憾,在调用apps.firewall.ingressRules.list 时无法使用 API 密钥。您需要使用 OAuth,因为该方法需要以下 OAuth 范围:

    • appengine.admin
    • 云平台
    • cloud-platform.read-only

    Here 是关于使用服务帐户凭据进行身份验证的一个很好的答案。注意:

    注意范围参数。这定义了授予结果凭证对象的权限。

    SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
    SERVICE_ACCOUNT_FILE = 'service-account-credentials.json'
    
    from google.oauth2 import service_account
    
    cred = service_account.Credentials.from_service_account_file(
                SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    

    作为附加参考,这里是 REST API:

    https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.firewall.ingressRules/list

    这是 RPC 等价物:

    https://cloud.google.com/appengine/docs/admin-api/reference/rpc/google.appengine.v1beta#firewall

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2019-05-02
      • 2011-02-12
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多