我目前使用的 Google 服务帐户已启用域范围委派(我点击了此链接https://developers.google.com/identity/protocols/oauth2/service-account https://developers.google.com/identity/protocols/oauth2/service-account,以及这个链接https://developers.google.com/admin-sdk/reports/v1/guides/delegation 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 中的另一个用户。
另外,我不想像许多其他帖子所说的那样与我的服务帐户共享文件夹。不应该是这样,因为我冒充了主人。