尝试使用 Python 访问目录 api 时,服务帐户未获得访问此 resource/api 的授权
Service account not Authorized to access this resource/api while trying to access directory api using Python
我们使用 Python 从特定的 G Suite 托管域获取所有用户,但在完成以下 tutorial 并授予服务帐户所需的所有访问权限后,以下代码段仍然会生成“无权访问此 resource/api:
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)
service = build('admin', 'directory_v1', credentials=credentials)
Google documentation 中有一条(非常模糊的)线索可以解决:
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 库进行身份验证时发送 "subject"。主题应该是有权访问管理员的用户 API(他不必是管理员,用户管理角色应该足够了,至少满足我的需要)。
工作片段:
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")
我们使用 Python 从特定的 G Suite 托管域获取所有用户,但在完成以下 tutorial 并授予服务帐户所需的所有访问权限后,以下代码段仍然会生成“无权访问此 resource/api:
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)
service = build('admin', 'directory_v1', credentials=credentials)
Google documentation 中有一条(非常模糊的)线索可以解决:
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 库进行身份验证时发送 "subject"。主题应该是有权访问管理员的用户 API(他不必是管理员,用户管理角色应该足够了,至少满足我的需要)。
工作片段:
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")