过去几天,我一直在使用管理SDK for Google Apps中的Google Directory API遇到麻烦。文档还有很多不足之处,当我联系Google Apps Enterprise支持时,他们表示他们不支持API。我正在使用Google提供的最新Python API客户端库,因为他们认为这是最好的方法。我已登录Google API控制台并创建了服务帐户并下载了OAuth2密钥。我还在控制台中打开了Admin 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”,因为谷歌似乎表示在使用超级管理员帐户时应该可以正常工作,但是当我以这种方式尝试时,我会收到返回“无效的customerId”。所以我硬编码了我们的实际customerId。
当编码时总是收到返回“需要登录”但似乎验证过程正在运行,因为目录对象是通过build命令创建的。难道我做错了什么?
注意,我还在某处读过,有时请求需要来自域帐户而不是服务帐户,为此需要添加:
sub = "domain_account_superadmin@example.com"
在SignedJwtAssertionCredentials中调用...我试过,但接收到“access_denied”消息
提前感谢您的建议。
答案 0 :(得分:3)
请在此处查看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)