无法使用 Google Admin SDK Directory API 和服务帐户访问用户数据

问题描述 投票:0回答:1

我在尝试通过服务帐户使用 Google Admin SDK Directory API 访问用户数据时遇到问题。这是场景:

我有一个 Python 脚本,它利用 Google Admin SDK Directory API 来检索用户数据。 我正在使用服务帐户来验证 API 请求。 我已按照 Google 文档中概述的步骤设置域范围委派,并且已向服务帐户授予必要的权限,包括“用户管理管理员”角色。 当我尝试检索非管理员用户的用户数据时,收到 403 错误,并显示消息“未授权访问此资源/api”。 这是我的 Python 脚本的简化版本:

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

# Replace 'path/to/your/service-account-key.json' with the path to your service account key file
SERVICE_ACCOUNT_KEY_FILE = 'path/to/your/service-account-key.json'
# Replace '[email protected]' with the email address you want to check
USER_EMAIL_TO_CHECK = '[email protected]'

# Load service account credentials
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_KEY_FILE,
    scopes=['https://www.googleapis.com/auth/admin.directory.user.readonly'],
)

# Impersonate the user
credentials = credentials.with_subject(USER_EMAIL_TO_CHECK)
# Build the Admin SDK Directory API client
directory_service = build('admin', 'directory_v1', credentials=credentials)

try:
    # Retrieve user information
    user = directory_service.users().get(userKey=USER_EMAIL_TO_CHECK).execute()
    print(user)
    # If the user exists, print their information
    print(f'User exists in Active Directory: {user["primaryEmail"]}')
except Exception as e:
    # If an exception occurs, the user does not exist
    print(f'User does not exist in Active Directory: {USER_EMAIL_TO_CHECK}')
    print(f'Error: {e}')

我已验证服务帐户是否已通过域范围委派正确设置并具有必要的权限。 我还确保我尝试模拟的用户存在于 Active Directory 中。

任何人都可以深入了解为什么我在尝试使用 Google Admin SDK Directory API 和服务帐户访问非管理员用户的用户数据时收到 403 错误,尽管我已经设置了域范围的委派并授予了必要的权限? 我还获取了管理员电子邮件 ID 的详细信息,但工作区中的其他电子邮件却收到了 403 错误

python google-cloud-platform google-api google-oauth google-admin-sdk
1个回答
0
投票

使用 Google Workspace,您需要委派给域上的用户。这是使用 create_delegate 完成的

def build_service_service_account_workspace(credentials, scope, delegated_user):
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        credentials,
        scopes=scope,
    )
    credentials = credentials.create_delegated(delegated_user)
    try:
        return build('drive', 'v3', credentials=credentials)
    except HttpError as error:
        # TODO(developer) - any errors returned.
        print(f'An error occurred: {error}')
© www.soinside.com 2019 - 2024. All rights reserved.