栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

GAE AttributeError:“凭据”对象没有属性“ with_subject”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

GAE AttributeError:“凭据”对象没有属性“ with_subject”

的确,您不能使用

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
功能,不受代表团创建凭证,以便该功能可有或无授权使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号