本文介绍了尝试使用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文档:

在OAuth2库中进行身份验证时,通过发送主题"来实现Python中的模拟.主题应该是有权访问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="[email protected]")

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

08-15 23:58