0

下面的示例演示了使用上面几行使用 python api 创建的密钥对谷歌服务帐户进行身份验证失败。

我找不到任何关于如何使用这些编程密钥的文档。

通过单击控制台 UI 创建的键工作正常。但是,对于我们的用例,我们需要使用编程方式创建密钥。

github 上也有未解决的问题:https ://github.com/googleapis/google-cloud-python/issues/7824

logger.info("Created new service account: {}".format(ret))

logger.info("Getting the new service account key")

request=iam.projects().serviceAccounts().keys().create(name=ret['name'],
    body={'privateKeyType':'TYPE_GOOGLE_CREDENTIALS_FILE'})

key=request.execute()

>>>print json.dumps(key, indent=4) #just to verify what we got

{
    "keyOrigin": "GOOGLE_PROVIDED", 
    "name": "goodandvalidname", 
    "validBeforeTime": "2029-06-28T15:09:59Z", 
    "privateKeyData": "datadata", 
    "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE", 
    "keyAlgorithm": "KEY_ALG_RSA_2048", 
    "validAfterTime": "2019-07-01T15:09:59Z"
}

>>> credentials = google.oauth2.service_account.Credentials.from_service_account_info(key)
Traceback (most recent call last):
  File "/home/user/.p2/pool/plugins/org.python.pydev.core_7.2.1.201904261721/pysrc/_pydevd_bundle/pydevd_exec.py", line 3, in Exec
    exec exp in global_vars, local_vars
  File "<console>", line 1, in <module>
  File "/home/user/.local/lib/python2.7/site-packages/google/oauth2/service_account.py", line 193, in from_service_account_info
    info, require=['client_email', 'token_uri'])
  File "/home/user/.local/lib/python2.7/site-packages/google/auth/_service_account_info.py", line 51, in from_dict
    'fields {}.'.format(', '.join(missing)))
ValueError: Service account info was not in the expected format, missing fields token_uri, client_email.

任何帮助表示赞赏。

4

1 回答 1

2

回答我自己的问题并可能帮助其他人......

我们从 python API 获得的“密钥”不是从gcloud. 我们从中获得的 dictiam.projects().serviceAccounts().keys().create()包含本身包含 ENTIRE 'json key' 的字段privateKeyData,需要向谷歌云进行身份验证。

该字段中的数据是base64编码的,需要解码,然后转储到json。以下是功能代码的片段,展示了从此类密钥加载的凭据:

request=iam.projects().serviceAccounts().keys().create(name=ret['name'], 
   body={'privateKeyType':'TYPE_GOOGLE_CREDENTIALS_FILE'})

key=request.execute()

key=base64.decodestring(key['privateKeyData'])
key=json.loads(key)

credentials = google.oauth2.service_account.Credentials.from_service_account_info(key)

我通过gcloud使用 python 调试器逐行创建服务帐户密钥来解决这个问题。希望这对其他人有帮助。

于 2019-07-02T14:38:36.317 回答