【发布时间】:2018-04-22 20:02:55
【问题描述】:
我正在尝试编写一个简单的脚本,该脚本将使用 google-api-python-client 从我的 Google G Suite 域从 Admin SDK 的 Directory API 获取用户列表。我阅读了大量文档,尝试了数百种不同的请求,但总是收到:googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=example.com&alt=json returned "Not Authorized to access this resource/api"> 错误。
这就是我所做的:
-
在 Google 开发者控制台https://console.developers.google.com:
- 创建了一个新项目
- 已启用“Admin SDK”API。
- 创建了服务帐号密钥
- 将生成的密钥保存到“service-key.json”文件中
-
在 G Suite 管理控制台中:
- API 访问已启用
- 管理 SDK 已启用
- 服务密钥 ^^ 的“客户端 ID”被授权“查看您域上的用户”,范围:API 客户端访问控制台部分中的https://www.googleapis.com/auth/admin.directory.user.readonly。
-
创建了一个简单的测试脚本:
#!/usr/bin/env python3 import json from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'service-key.json', scopes) account = credentials.authorize(Http()) service = build('admin', 'directory_v1', http=account) response = service.users().list(domain='example.com').execute() print(response)
其他:
- 还尝试了“启用 G Suite 域范围委派”(在 ServiceAccountCredentials 对象上使用了 create_delegated() 方法)
- 我在 Google 开发者控制台 - 仪表板中看到,脚本正在发出正确的请求 - 可以看到正在发出 'directory.users.list' API 方法,但失败并出现 403 错误
提前感谢您的帮助!
【问题讨论】:
-
尝试impersonating 成为您域的管理员,因为您已经能够启用域范围的委派。如链接所述,“当您的服务帐户请求并且不是域的管理员时,它无法访问 Admin SDK Directory API。”希望这会有所帮助。
-
你如何在 python 中做到这一点?例如。上面的代码会是什么样子?
-
@Elliptica 您可以查看this 答案以获取 Python 解决方案
标签: python python-3.x google-api google-admin-sdk google-api-python-client