![](/img/trans.png)
[英]Accessing Google Sheets API through a service account impersonating a user through domain-wide delegation fails
[英]Google API Service Account. Can only see service accounts drive even with Domain Wide Delegation Access
我目前正在使用啟用了域范圍委派的 Google 服務帳戶(我點擊了此鏈接https://developers.google.com/identity/protocols/oauth2/service-account和此鏈接https://developers.google .com/admin-sdk/reports/v1/guides/delegation ),並啟用了“ https://www.googleapis.com/auth/drive范圍。我已經下載了服務帳戶的 json 憑據並將它們放在與我的 python 腳本相同的目錄。問題是當我模擬另一個用戶時,可以說我的域中的 User2,然后我嘗試列出 User2 驅動器中的文件。我只獲取服務帳戶驅動器中的文件。
我有一段模擬 User2 的代碼。
def auth():
domain = 'domain'
# impersonate this user
user = 'testuser' # id only (ie. without @domain)
#scopes = ['https://www.googleapis.com/auth/drive',]
key_file = 'service_account.json'
subject = ''.join([user,'@',domain])
delegated_credentials = service_account.Credentials.from_service_account_file(key_file)
delegated_credentials.with_subject(subject)
drive_service = googleapiclient.discovery.build('drive', 'v2', credentials=delegated_credentials)
return drive_service
后來我試圖獲取用戶 mydrive 中的文件列表。
children = service.children().list(folderId='root', **param).execute()
for child in children.get('items', []):
item = service.files().get(fileId=child['id']).execute()
以上項目始終是服務帳戶的“我的驅動器”中的“入門 PDF”
基本上,這樣做的全部目的是以編程方式將任何文件夾(及其內容)的所有權更改為同一 G-Suite 中的另一個用戶。
此外,我不想像許多其他帖子所說的那樣與我的服務帳戶共享文件夾。 這不應該是這種情況,因為我在冒充所有者。
如果這不是發布問題的正確方式,我深表歉意。 這是我的第一篇文章。
您的身份驗證流程有兩個問題:缺少范圍和錯誤分配的變量。
delegated_credentials
變量時,您的委托憑證缺少范圍。 正如您在准備進行授權 API 調用文檔中所見,在定義credentials
對象時,您必須指定將在請求中使用的范圍。
然后,在將范圍添加到憑據時,您需要將其分配給一個變量,該變量可以傳遞給 Drive 服務的構建。
要修復第 1 點,您需要取消對范圍的注釋並更改此行:
delegated_credentials = service_account.Credentials.from_service_account_file(key_file)
包括范圍:
scopes = ['https://www.googleapis.com/auth/drive']
delegated_credentials = service_account.Credentials.from_service_account_file(
key_file, scopes=scopes)
此外,在構建驅動服務之前,您需要將delegated_credentials.with_subject(subject)
分配給自身:
delegated_credentials = delegated_credentials.with_subject(subject)
drive_service = googleapiclient.discovery.build(
'drive', 'v2', credentials=delegated_credentials)
我希望這對你有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.