使用服务帐户模拟Google Drive获取刷新令牌

2024-05-15 01:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个脚本,将在我们公司的多个用户Gdrive中搜索文件。问题是,该脚本只能工作一段时间,但随后会出现HTTP 401错误,很可能是由于访问令牌过期。我正在使用一个启用了域范围委托的服务帐户,并使用google.oauth2 python库创建一个驱动器服务对象(请参见下面的代码)。我想通过编程获得一个刷新令牌,并在当前令牌过期时生成新的访问令牌。问题是没有关于如何使用服务帐户实现这一点的文档。在正常的用户交互oauth流中,存在一个可用的方法。我的问题是如何使用驱动器对象检索刷新令牌,然后创建新的访问令牌。我知道我将不得不以某种方式使用我的服务帐户的私钥,但不确定

我一直在看这两份文件。 https://developers.google.com/identity/protocols/oauth2https://developers.google.com/identity/protocols/oauth2/service-account

  • 使用模拟用户创建驱动器服务对象
from google.oauth2 import service_account
import googleapiclient.discovery

def impersonate_user(user_to_impersonate, key_file, domain):
        scopes = ['https://www.googleapis.com/auth/drive',]

        if user_to_impersonate is None:
            raise InvalidDomainUser(f"{user_to_impersonate} is not a member of {domain}")

        if key_file is None:
            raise FileNotFoundError(f"{key_file} is not a valid service account file")

        delegated_credentials = service_account.Credentials.from_service_account_file(
            key_file, scopes=scopes)
        # Impersonate User.
        delegated_credentials = delegated_credentials.with_subject(user_to_impersonate)
        drive_service = googleapiclient.discovery.build('drive', 'v2', credentials=delegated_credentials)

        # Set new drive resource object
        return drive_service
  • 列出用户驱动器中的文件
service = impersonate_user(user_to_impersonate, key_file, domain):
children = service.children().list(folderId=folderId,maxResults=1000, **param).execute() 
for child in items:
            item = service.files().get(fileId=child['id']).execute()
            print(item.get("title", None))



Tags: tokey用户isservicegoogleaccountdrive
2条回答

这是python服务帐户的基本代码。您需要添加委派部分

只要您使用相同的服务,库就应该在需要时为您获取一个新的访问令牌。它不应该过期

"""Hello drive"""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def drive():
  """Initializes an drive service object.

  Returns:
    An authorized drive service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  drive = build('drive', 'v3', credentials=credentials)

  return drive

模拟用户会生成过期的访问令牌。要获得一个新的访问令牌,只需按照与第一次相同的方式生成一个。服务帐户没有刷新令牌的概念,您只需使用凭据生成一个新的访问令牌

来源:构建Google Service Account support at Xkit

相关问题 更多 >

    热门问题