且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试使用 Python 访问目录 api 时,服务帐户无权访问此资源/api

更新时间:2022-11-25 22:58:19

Google 文档到解决方案:

注意:只有有权访问 Admin API 的用户才能访问 AdminSDK Directory API,因此您的服务帐户需要模拟访问 Admin SDK Directory API 的用户之一.此外,用户必须至少登录一次并接受G Suite 服务条款.

Note: Only users with access to the Admin APIs can access the Admin SDK Directory API, therefore your service account needs to impersonate one of those users to access the Admin SDK Directory API. Additionally, the user must have logged in at least once and accepted the G Suite Terms of Service.

在 Python 中实现模拟的方法是在使用 OAuth2 库进行身份验证时发送主题".主题应该是有权访问 Admin API 的用户(他不必是管理员,用户管理角色应该就足够了,至少满足我的需要).

The way to achieve the impersonation in Python is by sending a "subject" when authenticating with OAuth2 library. The subject should be a user with an access to the Admin API (He doesn't have to be an admin, User Management Role should be sufficient, at least for my needs).

工作片段:

import json
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES, subject="admin@yourdomain.com")