如何使用服务帐号生成的密钥通过 googleapi 客户端进行身份验证



我正在创建新的谷歌服务帐户,并希望使用新创建的服务帐户进行身份验证

def create_service_account(project_id, name, display_name):
"""Creates a service account."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'iam', 'v1', credentials=credentials)
my_service_account = service.projects().serviceAccounts().create(
name='projects/' + project_id,
body={
'accountId': name,
'serviceAccount': {
'displayName': display_name
}
}).execute()
print('Created service account: ' + my_service_account['email'])
return my_service_account

说我的服务帐户名称是XXXX@com 我正在使用为此服务帐户生成密钥

def create_key(service_account_email):
"""Creates a key for a service account."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'iam', 'v1', credentials=credentials)
key = service.projects().serviceAccounts().keys().create(
name='projects/-/serviceAccounts/' + service_account_email, body={}
).execute()
print('Created key: ' + key['name'])

上面的代码工作正常。

我想使用新创建的服务帐户进行其他操作。 如何验证新创建的服务帐户? 除此之外,还有其他创建凭据的方法吗

credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'iam', 'v1', credentials=credentials)

我建议你使用默认的凭据方法,你的代码可以这样

import google.auth
credentials, project_id = google.auth.default()

这里有描述。代码

  1. 首先检查是否定义了GOOGLE_APPLICATION_CREDENTIALS
  2. 如果没有,请检查您的环境中的 gcloud 应用程序默认凭据。
  3. 如果没有,请检查代码是否在 GCP 环境中运行(如果元数据服务器存在(
  4. 错误

在这里,重要的是要注意第 2 点和第 3 点。

  • 在本地环境中,不需要服务帐户密钥文件。您可以将自己的用户凭据与 GCLOUD 一起使用作为默认凭据
  • 在 GCP 环境中,您也不需要服务帐户密钥文件,因为您可以使用组件标识(请查看组件文档以指定 yon 想要的服务帐户电子邮件(

最后,如果您的应用处于非 GCP 环境(内部部署、其他云提供商(中,则必须使用服务帐户密钥文件并在环境变量中定义它。但不必在代码中显式调用它。在这里,默认凭据再次有效!

注意

我强烈建议您避免生成服务帐户安全文件。这是保安的噩梦。它只是一个对您进行身份验证的文件。文件可以复制,通过电子邮件发送,甚至可以在公共git存储库中提交。此外,建议至少每 90 天轮换一次这些密钥文件 (...(。如果您不在 GCP 之外运行您的应用程序,请避免使用它,它会节省您!

编辑

如果出现错误,这是因为您使用创建服务帐户密钥文件的答案作为密钥。这是一个常见的错误。您只需使用答案中privateKeyData字段,并将其解码(以 64 为基数(。

然后,您有一个有效的服务帐户 JSON 密钥文件。

如果要使用该密钥,则必须在凭据创建中提供此密钥

# either you have save your json into a file
credentials = service_account.Credentials.from_service_account_file(
filename=/path/to/file/key.json,
scopes=['https://www.googleapis.com/auth/cloud-platform'])
# or if you have kept the json into memory and convert it into a dict
credentials = service_account.Credentials.from_service_account_info(dict_json_key,
scopes=['https://www.googleapis.com/auth/cloud-platform'])

最新更新