使用Oauth2作为服务帐户(教育版)的Google管理员API - 403错误

Bru*_*uce 7 python-2.7 google-oauth

我在使用Google新的管理SDK时遇到了困难.特别是使用Oauth2的Directory API.我想我差不多了但是我一直试图使用Directory API(我正在使用Google Education Edition域)检索用户详细信息.

基本上我想要做的是编写规定或者去规定用户在此基础上由我们的广告管理他们的注册状态的Python脚本.我有一个脚本,使用Oauth1执行此操作,但想要更新它以使用Oauth2.

这是基于我发现的一些示例的代码片段.

f = file('test_key.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
     '606346240424-10stfco1ukj9h4m4b4r40@developer.gserviceaccount.com',
     key,
     scope= 'https://www.googleapis.com/auth/admin.directory.user')
http = httplib2.Http()
http = credentials.authorize(http)
service = build(serviceName='admin', version='directory_v1', http=http)

lists = service.users().get(userKey='joe.blogs@mydomain.com').execute(http=http)
pprint.pprint(lists)
Run Code Online (Sandbox Code Playgroud)

这段代码似乎正确连接但是当我尝试执行查询时,我收到403错误.

错误:https://www.googleapis.com/admin/directory/v1/users/joe.blogs@mydomain.com ?alt = json返回"未授权访问此资源/ api">

我的第一个想法是因为我没有在管理员控制台(Google API的控制台)上打开此API,但我有.(实际上我打开了Admin SDK而不是Directory API,因为没有要打开的Directory API,并且发现它是Admin SDK的一部分,它会起作用吗?).

我还缺少另一个步骤,还是在某个地方犯了一个愚蠢的错误?

小智 6

布鲁斯,

你很近.

几件物品:

所以完整的代码看起来有点像这样:

    # domain configuration settings
    import domainconfig

    f = file(domainconfig.KEY_FILE, "rb") # b reads file in binary mode; not strictly necessary, but safer to avoid strange Windows EOL characters: https://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and-rb-mode
    key = f.read()
    f.close()

    credentials = SignedJwtAssertionCredentials(

        domainconfig.SERVICE_ACCOUNT_EMAIL,
        key,
        scope = domainconfig.SCOPE, 
        sub=domainconfig.SUB_ACCOUNT_EMAIL # 'sub' supercedes the deprecated 'prn'

    )

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

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

    users = directoryservice.users()
    response = users.get(userKey='joe.blogs@mydomain.com').execute() 
Run Code Online (Sandbox Code Playgroud)