的确,您不能使用
with_subject具有GAE或GCE凭据的方法。但是,有一种解决方法可以在GCE服务器上工作,并且我认为这也适用于GAE默认服务帐户。解决方案是使用带有
subject和的服务帐户标识来构建新的凭据
scopes。可以在此处找到详细的指南,但下面还将介绍该过程。
首先,服务帐户需要权限才能为其自身创建服务帐户令牌。这可以通过转到项目
IAM and admin > Serviceaccounts页面来完成(确保信息面板可见,可以从右上角进行切换)。复制服务帐户的电子邮件地址,并通过选中复选框来选择有问题的服务帐户。现在信息面板上应该有
ADDMEMBER按钮。单击它,然后将服务帐户电子邮件粘贴到
New members文本框中。单击
Selectrole下拉列表,然后选择角色
Service Accounts -> Service Account TokenCreator。您可以使用以下
gcloud命令检查是否已分配角色:
gcloud iam service-accounts get-iam-policy [SERVICE_ACCOUNT_EMAIL]
现在到实际的Python代码。本示例是对上面链接的文档的略微修改。
from googleapiclient.discovery import buildfrom google.auth import default, iamfrom google.auth.transport import requestsfrom google.oauth2 import service_accountTOKEN_URI = 'https://accounts.google.com/o/oauth2/token'SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']GSUITE_ADMIN_USER = 'admin@example.com'def delegated_credentials(credentials, subject, scopes): try: # If we are using service account credentials from json file # this will work updated_credentials = credentials.with_subject(subject).with_scopes(scopes) except AttributeError: # This exception is raised if we are using GCE default credentials request = requests.Request() # Refresh the default credentials. This ensures that the information # about this account, notably the email, is populated. credentials.refresh(request) # Create an IAM signer using the default credentials. signer = iam.Signer( request, credentials, credentials.service_account_email ) # Create OAuth 2.0 Service Account credentials using the IAM-based # signer and the bootstrap_credential's service account email. updated_credentials = service_account.Credentials( signer, credentials.service_account_email, TOKEN_URI, scopes=scopes, subject=subject ) except Exception: raise return updated_credentialscreds, project = default()creds = delegated_credentials(creds, GSUITE_ADMIN_USER, SCOPES)service = build('admin', 'directory_v1', credentials=creds)
try如果您
GOOGLE_APPLICATION_CREDENTIALS设置的环境变量带有服务帐户文件的路径,则该块不会失败。如果该应用程序在Google
Cloud上运行,则会出现一个,
AttributeError并通过创建具有
subject和的新凭据来进行处理
scopes。
您也可以通过
None为
subject对
delegated_credentials功能,不受代表团创建凭证,以便该功能可有或无授权使用。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)