繁体   English   中英

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

[英]Can't seem to impersonate user or not getting token with google oauth2 in python using a service account

谷歌 API 和 Python 非常新,但在一些小动作上取得了一些成功,比如用我自己的信用在谷歌驱动器下获取文件等

我是 Google Workspace 管理员,我已将全域委派授予具有完全访问驱动器 scope 的服务帐户: https://www.googleapis.com/auth/drive全域委派

scope 也在 88142662888 同意屏幕下授予相同的 scope: https://www.googleapis.com/auth/drive oauth 同意屏幕

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

我遇到的问题是我想模拟一个用户来获取他们正在进行的项目的文件列表,经过大量的努力,我现在没有收到任何错误,但似乎没有正确地模拟用户和/还是没有得到令牌?

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

我已经在这里搜索了我的帖子,人们问了类似的问题,但还没有真正找到答案,但恐怕我现在很想问这个问题。

我尝试使用的代码如下:

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()

我得到的 output 是:

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)

我现在可以成功查看用户文件和文件夹

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM