我想使用admin sdk目录api来创建用户的eamil帐户。
我正在使用google-api-python-client-1.2库。
文件夹/samples/service_account/tasks.py中的对我有用。
但是当我冒险从admin目录api列出用户的文件时,它不起作用并抛出错误。
下面是我正在使用的代码。
import httplib2
import pprint
import sys
import inspect
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
def main(argv):
f = file('my-privatekey.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'my@developer.gserviceaccount.com',
key,
scope=['https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.readonly'])
http = httplib2.Http()
http = credentials.authorize(http)
service = build("admin", "directory_v1", http)
list_of_apis = service.users().list(domain='mydomain.com').execute(http=http)
pprint.pprint(list_of_apis)
if __name__ == '__main__':
main(sys.argv)
当我运行上面的代码时,我得到以下错误。
$python tasks.py
No handlers could be found for logger "oauth2client.util"
Traceback (most recent call last):
File "tasks.py", line 77, in <module>
main(sys.argv)
File "tasks.py", line 66, in main
list_of_apis = service.users().list(domain='messycoders.com').execute(http=http)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri) apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=messycoders.com&alt=json returned "Not Authorized to access this resource/api">
答案 0 :(得分:3)
尝试:
credentials = SignedJwtAssertionCredentials(
'my@developer.gserviceaccount.com',
key,
sub='superadmin@mydomain.com',
scope=['https://www.googleapis.com/auth/admin.directory.user',])
如果您只进行读操作,则不需要两个范围,只使用readonly,如果您正在进行读写操作,请使用上述内容。
sub =定义服务帐户应该模拟执行目录操作的Google Apps帐户,这是必要的,并且帐户需要具有正确的权限。
最后,请确保您已授予服务帐户对client_id访问控制面板中所需的目录范围的权限。 steps to do this are listed in the Drive documentation,只是在管理员目录的正确范围内。