Google 使用 Python 服务帐户的用户列表

Google user listing with service account using Python

我有一个 Json 服务文件和一个已经访问翻译和表格的服务帐户,但它不会访问用户列表。结果要么是 400 表示它感到困惑,要么是 401 表示它没有被授权。示例通常是关于客户端涉及的 OAuth 进程,我需要服务器到服务器。我也在服务帐户上启用了“启用 G Suite 全域委派”功能。

我阅读并尝试了 JWT 方法,但得到了相同的错误响应。 https://developers.google.com/identity/protocols/oauth2/service-account#python_2

我的目标是调用这些端点之一 https://www.googleapis.com/admin/directory/v1/users https://www.googleapis.com/admin/directory/v1/users.readonly

任何方向将不胜感激。

更新 1: 这是使用产生错误 401 的 Jwt 令牌方法。

with open(CLIENT_SECRET_FILE, "r+") as fh:
    config = json.load(fh)

iat = time.time()
exp = iat + 3600
payload = {'iss': config['client_email'],
           'sub': config['client_email'],
           'aud': 'https://www.googleapis.com/',
           'iat': iat,
           'exp': exp}
additional_headers = {'kid': config['private_key_id']}
signed_jwt = jwt.encode(payload, config['private_key'], headers=additional_headers,
                        algorithm='RS256')

url = 'https://www.googleapis.com/admin/directory/v1/users'        
headers = {"Authorization": "Bearer " + signed_jwt}
r = requests.get(url, headers=headers)

我也试过了

scopes = ['https://www.googleapis.com/auth/admin.directory.user']
credentials = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_FILE, scopes=scopes)
service = build('admin', 'directory_v1', credentials=credentials)
results = service.users().list().execute()

更新 2: 此 link 包含大量信息和简单的代码供您查看。尽管我尽量避免模拟,但 AdminSDK 需要它。在我看来,这使得集成有点尴尬。此外,我还面临的问题是 Google Workspace Admin 中的 Domain-Wide-Delegation 屏幕可能会变得混乱。删除条目并重新创建它修复了永远的 403 错误,无论我尝试了什么,我都会不断收到。 https://gist.github.com/lewisrodgers/fa766ebd37c1397d3a014eb73805edd1

您需要将模拟合并到您的代码中,以便服务帐户代表管理员

因为只有管理员有权访问 Resource: users

对于 Python 中的 impersonation 您需要实施附加行

delegated_credentials = credentials.with_subject('admin@example.org')

下面的 link 包含大量信息和简单的代码供您查看。尽管我尽量避免模拟,但 AdminSDK 需要它。在我看来,这使得集成有点尴尬。

此外,我还面临的问题是 Google 工作区管理中的全域委派屏幕搞砸了。经过数周的深入挖掘,我找到了一个简单的解决方案,即删除并重新创建该屏幕中的客户端条目。它修复了永无止境的 403 错误,该错误击中了我尝试过的每个测试,这些测试本应有效并且对其他许多人都有效。

这似乎是 Google 设置的唯一需要模拟的 API,并且在尝试创建 SaaS 解决方案时很烦人。

真正基础的、精简的示例和体面的文章参考。 https://gist.github.com/lewisrodgers/fa766ebd37c1397d3a014eb73805edd1