似乎无法使用服务帐户在python中模拟用户或无法通过谷歌oauth2获得令牌



对Google API和Python非常陌生,但在一些小操作上取得了一些成功,比如用我自己的信用将文件放在Google drive下等

我是一个谷歌工作空间管理员,我已经授予域范围的授权与完整的访问驱动器范围的服务帐户:https://www.googleapis.com/auth/drive域方面代表团

范围也在相同范围的初始同意屏幕下授予:https://www.googleapis.com/auth/driveOauth同意屏幕

我还按正确的顺序添加了它们,因为这有时可能是一个问题,显然在研究这一切

我遇到的问题是我想模拟用户以获取正在进行的项目的文件列表,经过大量的战斗,我现在没有得到任何错误,但似乎没有正确地模拟用户和/或没有获得令牌?

这可能是我在这方面仍然是一个新手,但我不明白为什么我似乎不能冒充一个用户,并看到他们的文件仍然使用下面的代码。

我浏览了我在这里的帖子,人们问了类似的问题,但还没有真正找到答案,恐怕所以我现在想问这个。

我想使用的代码如下:

from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('serviceaccount.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive'])
delegated_credentials = scoped_credentials.with_subject('someone@company.com')
print(delegated_credentials.token)
drive = build('drive', 'v3', credentials = delegated_credentials)
drive.files().list().execute()

if __name__ == '__main__':
main()
我得到的输出是:
python.exe .impersonate.py
None

所以没有错误,但我也没有得到可能看到令牌的预期结果(如果这是它应该如何工作的话),至少我认为我现在可以在我指定的主题中看到用户的文件和文件夹。

任何帮助都将非常感激!

好的,所以在我发布这篇文章后不久,我看到了一些我认为我应该在代码中尝试的东西,它是有效的!

有点尴尬,但这可能会帮助别人在未来的问题:)

我的修复是添加:delegated_credentials.refresh(Request())

credentials = service_account.Credentials.from_service_account_file('serviceaccount.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive'])
delegated_credentials = scoped_credentials.with_subject('someone@company.com')
delegated_credentials.refresh(Request())
print(delegated_credentials.token)

我现在能够成功地看到用户文件和文件夹

最新更新