在管理SDK中使用Google目录API的正确方法是什么?

2024-05-20 02:03:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在过去的几天里,我在使用googleapps的管理SDK中的googledirectoryapi时遇到了麻烦。文档还有很多需要改进的地方,当我联系googleapps企业支持时,他们表示不支持API。我正在使用Google提供的最新pythonapi客户端库,因为他们认为这是最好的方法。我已经登录到googleapi控制台并创建了一个服务帐户并下载了OAuth2密钥。我还打开了控制台中的管理SDK。这是我的代码:

f = file("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12", "rb")
key = f.read()
f.close()

credentials = SignedJwtAssertionCredentials(
    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com",
    key,
    scope = "https://www.googleapis.com/auth/admin.directory.orgunit"
)

http = httplib2.Http()
http = credentials.authorize(http)

directoryservice = build("admin", "directory_v1", http=http)

orgunits = directoryservice.orgunits().list(customerId='XXXXXXX').execute(http=http)
pprint.pprint(orgunits)

请注意,customerId是我们的Google Apps客户ID。我用“my_customer”尝试过,因为Google似乎在使用super admin帐户时应该可以正常工作,但是当我这样做时,我收到的返回是“invalid customerId”。所以我硬编码了我们的实际客户ID。在

当harcoded总是收到“Login Required”的返回,但似乎身份验证过程正在工作,因为目录对象是通过build命令创建的。我做错什么了吗?在

请注意,我还读到,有时请求需要来自域帐户,而不是服务帐户,为此,您需要添加:

^{pr2}$

在SignedJwtAssertionCredentials调用中。。。我试过了,但是收到了“拒绝访问”的消息

提前感谢您的建议。在


Tags: keycomhttpadminservicegooglesdk帐户
1条回答
网友
1楼 · 发布于 2024-05-20 02:03:55

请参阅下面的google驱动器示例:https://developers.google.com/drive/delegation 别忘了为服务帐户和作用域委派域范围的权限。 以下是通过服务帐户列出组织单位的示例:

import sys
import apiclient.discovery
import oauth2client.client
import httplib2
import pprint

# see example for using service account here: 
#   https://developers.google.com/drive/delegation
def main (argv):
    scopes = ('https://www.googleapis.com/auth/admin.directory.orgunit')
    service_account_email = 'xxx@developer.gserviceaccount.com'
    acting_as_user = 'yyy@zzz' # must have the privileges to view the org units
    f = file('key.p12', 'rb')
    key = f.read()
    f.close()
    credentials = oauth2client.client.SignedJwtAssertionCredentials(
        service_account_email,
        key,
        scope=scopes,
        sub=acting_as_user
        )
    http = httplib2.Http()
    http = credentials.authorize(http)
    directoryservice = apiclient.discovery.build('admin', 'directory_v1', http=http)
    response = directoryservice.orgunits().list(customerId='my_customer').execute(http=http)
    pprint.pprint(response)

if __name__ == '__main__':
    main(sys.argv)

相关问题 更多 >