我正在创建新的google服务帐户,并希望使用新创建的服务帐户进行身份验证
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)发布于 2020-05-15 03:19:38
我建议您使用默认的凭据方法,您的代码可能如下所示
import google.auth
credentials, project_id = google.auth.default()您有here这样的描述。代码
如果定义了GOOGLE_APPLICATION_CREDENTIALS,则首先检查
在这里,重要的是要注意第二点和第三点。
最后,如果您的应用程序在非GCP环境中(本地,在其他云提供商上),您必须使用服务帐户密钥文件并在环境变量中定义它。但您不必在代码中显式调用它。在这里,默认凭据仍然有效!
笔记
强烈建议您避免生成服务帐号安全文件。这对保安来说是个噩梦。它只是一个验证您身份的文件。文件可以复制,可以通过电子邮件发送,甚至可以在公共git repo上提交。此外,建议至少每90天轮换一次这些密钥文件(...)。如果你不在GCP之外运行你的应用,避免使用它,它会拯救你!
编辑
如果出现错误,那是因为您使用了create service account key file的答案作为密钥。这是常见的错误。您只需在答案中使用字段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'])https://stackoverflow.com/questions/61800002
复制相似问题