簡體   English   中英

嘗試使用 Python 訪問目錄 api 時,服務帳戶無權訪問此資源/api

[英]Service account not Authorized to access this resource/api while trying to access directory api using Python

我們使用 Python 從特定 G Suite 托管域中獲取所有用戶,但在完成以下教程並授予服務帳戶所需的所有訪問權限后,以下代碼段仍會生成“未授權訪問此資源/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 服務條款。

在 Python 中實現模擬的方法是在使用 OAuth2 庫進行身份驗證時發送“主題”。 主題應該是有權訪問 Admin 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM