0

我设法通过 Python API iamcredetials.googleapis.com 创建了一个服务帐户和一个自身的密钥,但我无法登录它,因为密钥是 P12 格式并dict以 .登录密钥。有没有办法创建 p12 文件或其他东西,以便我可以使用密钥?

我尝试使用模块中可用的函数,oauth2clinet.service_account.ServiceAccountCredentials()但它们都没有成功加载它,我知道这个库中有一定程度的弃用,也许我正在使用过时的方法。

我越接近成功登录是在使用 _from_p12_keyfile_contents() 给出“编码例程”错误的功能时,这超出了我的理解。

from oauth2client.service_account import ServiceAccountCredentials

from googleapiclient import discovery, errors, logging


default_creds = google_application_defaults()

service = discovery.build("iam", "v1", credentials=default_creds, cache_discovery = False)

key = service.projects().serviceAccounts().keys().create( name = serviceAccMail, body={}).execute()

creds = ServiceAccountCredentials._from_p12_keyfile_contents(accountEmail, newkey["privateKeyData"], "notasecret")

Error: [('asn1 encoding routines', 'asn1_check_tlen', 'wrong tag'), ('asn1 encoding routines', 'asn1_item_embed_d2i', 'nested asn1 error')]

登录此密钥的正确方法是什么?

4

1 回答 1

2

PFX (P12) 服务帐户格式已弃用。返回 Google 控制台并下载 Json 格式的服务帐户凭据。

下载 Json 格式的凭据后,更改您的代码:

from google.oauth2 import service_account

sa_file = 'full/path/to/service_account.json'

default_creds = service_account.Credentials.from_service_account_file(sa_file)

[更新:以下代码将显示如何使用 P12 凭据]

注意:P12 凭证不适用于所有 Google API(凭证类型不同)。此示例适用于 Google Discovery API。例如,此示例将无法使用google.cloud.storage

'''
Test program to use P12 credentials with Google Cloud Storage
'''
from oauth2client.service_account import ServiceAccountCredentials
import googleapiclient.discovery

# Details on the Google Service Account. The email must match the Google Console.
project_id = 'development-123456'
sa_filename = 'compute-engine.p12'
sa_password = 'notasecret'
sa_email = 'development-123456@developer.gserviceaccount.com'

SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]

cred = ServiceAccountCredentials.from_p12_keyfile(
        sa_email,
        sa_filename,
        private_key_password=sa_password,
        scopes=SCOPES)

client = googleapiclient.discovery.build('storage', 'v1', credentials=cred)

buckets = client.buckets().list(project=project_id).execute()

print('')
print('Listing buckets:')
for bucket in buckets['items']:
    print(bucket['name'])
于 2018-12-21T20:44:30.803 回答