【发布时间】:2023-04-03 00:50:01
【问题描述】:
我的 Python 脚本从 G Suite 中检索有关用户和组的信息(目前正在使用 14 天免费帐户进行测试)。我将域范围的委派和 OAuth 2.0 用于服务器到服务器应用程序,因为我不想显示一个弹出窗口,让来自托管域的用户允许我查看他们的组和用户。
这些是我为了获取用户和组而遵循的步骤:
- 创建并下载所有必要的凭据,例如客户端 ID;
- 在我的 G Suite 管理控制台中,允许访问我的客户端 ID,并授予它访问与我的脚本相同范围的用户和组 API 的权限;
- 在我的脚本中,使用 .json 创建凭据并代表 G Suite 管理员提出请求;
- 开始调用 API。
现在,G Suite 管理员必须在其安全设置中允许某个客户端 ID 某些范围:这是我手工制作的,手动输入客户端 ID 和范围。在OAuth 2.0 for Server to Server Applications 教程中写道:
如果您已委派服务帐户的域范围访问权限并且您想模拟用户帐户,请使用现有 service_account.Credentials 对象的 with_subject 方法。
所以:我允许自己从 G 套件管理面板访问某些 API,我的脚本创建了使用这些 API 的凭据,但我下载的 .json 还不够:似乎通过域范围委派,我的脚本仍然具有 代表来自该托管域的用户提出请求,在我的例子中是托管域的管理员。我尝试创建凭据wihtout 来模拟用户,但我没有足够的权限来执行此操作,并且对 API 的调用返回了 401 或 403。
我认为委托访问不需要代表用户执行操作,因为服务帐户未与任何用户关联。
我能否在不模拟属于我正在使用的托管域的用户的情况下为服务帐户创建凭据?我的客户 ID 和包含我的私钥和其他内容的 .json 文件还不够吗?
这是我的代码:
from google.oauth2 import service_account
import googleapiclient.discovery
import json
""" CONSTANTS AND GLOBAL VARIABLES
"""
# The API we request to use
SCOPES = ['https://www.googleapis.com/auth/admin.directory.group.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly']
# json containing keys, account service email, id client and other stuff
SERVICE_ACCOUNT_FILE = 'my_file.json'
# The hosted domain we want to work with
DOMAIN = 'some_hd.it'
# The user I'm using to create credentials
USER_EMAIL = 'name.surname@some_hd.it'
""" SETTING AND GETTING CREDENTIALS
"""
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
if credentials is None:
print "BAD CREDENTIALS"
delegated_credentials = credentials.with_subject(USER_EMAIL)
"""
build('api_name', 'api_version', ...)
https://developers.google.com/api-client-library/python/apis/
"""
service = googleapiclient.discovery.build('admin', 'directory_v1',
credentials=delegated_credentials)
""" GETTING GROUPS AND USERS
"""
request = service.groups().list(domain=DOMAIN)
response = request.execute()
groups = response.get('groups', [])
if not groups:
print "No groups in %s" % (DOMAIN)
print
request = service.users().list(domain=DOMAIN)
response = request.execute()
users = response.get('users', [])
if not users:
print "No users in %s" % (DOMAIN)
else:
for user in users:
for email in user['emails']:
print email['address']
print 'User ID: %s' % (user['id'])
print 'Is admin? %s' % (str(user['isAdmin']))
print
【问题讨论】:
标签: google-api google-oauth google-admin-sdk service-accounts