下面的示例演示了仅使用上面几行使用python API创建的密钥无法验证Google服务帐户的身份。
我找不到任何有关如何使用这些编程键的文档。
通过单击控制台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.
任何帮助表示赞赏。
答案 0 :(得分:0)
正在回答我自己的问题并可能帮助其他人...
我们从python API获得的“密钥”不是从gcloud
获得的“ json密钥”。我们从iam.projects().serviceAccounts().keys().create()
获得的字典包含字段privateKeyData
,字段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)
本身包含一个完整的“ json密钥”,需要向Google Cloud进行身份验证。
此字段中的数据是base64编码的,需要解码,然后转储到json。下面是功能代码的片段,演示了从此类密钥加载的凭据:
gcloud
我通过使用Python调试器逐行创建clearInterval()
服务帐户密钥来解决这一问题。希望这对其他人有帮助。