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

查看:302
本文介绍了尝试使用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)

推荐答案

注意:只有有权访问Admin API的用户才能访问Admin SDK 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.

在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="admin@yourdomain.com")

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

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