尝试使用 Python 访问目录 api 时,服务帐户无权访问此资源/api [英] Service account not Authorized to access this resource/api while trying to access directory api using Python

查看:27
本文介绍了尝试使用 Python 访问目录 api 时,服务帐户无权访问此资源/api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 Python 从特定的 G Suite 托管域中获取所有用户,但在完成以下操作后教程 并授予服务帐户所需的所有访问权限,以下代码段仍会生成未授权访问此资源/api:

We use Python to get all users from a particular G Suite managed domain, but after completing the following tutorial and granting all the access needed to the Service Account, the following snippet still produces "Not Authorized to access this 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 文档到解决方案:

注意:只有有权访问 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")

这篇关于尝试使用 Python 访问目录 api 时,服务帐户无权访问此资源/api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆