当前位置: 首页 > 知识库问答 >
问题:

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

郗浩言
2023-03-14

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

我一直在看这两份文件。https://developers.google.com/identity/protocols/oauth2 https://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))


共有2个答案

赫连骏
2023-03-14

这是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
毛缪文
2023-03-14

冒充用户会生成过期的访问令牌。要获得新的访问令牌,只需像第一次一样生成一个。服务帐户没有刷新令牌的概念,您只需使用凭据生成新的访问令牌。

来源:Xkit上的谷歌服务账户支持

 类似资料:
  • 我编写了一个控制台ASP.NET应用程序来获取AccessTokens。我有clientId,我的应用程序的客户端秘密,我做了以下操作: var authContext=新的AuthenticationContext(“https://login.windows.net/common/oauth2/authorize”);var acquireTask=authContext.AcquireTok

  • 目前访问类型处于联机状态。当我需要访问驱动器上的文件/文件夹时,我将浏览器重定向到Google URL并获得访问代码: 一切运转良好!但我只需要第一次重定向。 当我谷歌时,在google Drive API文档中,我发现我可以通过浏览器重定向获得刷新令牌,并将其保存在数据库中。(换句话说,我可以使用脱机访问)。 而且每次当我需要从google drive读取数据时,我使用刷新令牌获得访问令牌,而无

  • 我的问题是如何使用OAuth2.0从刷新令牌中获取访问令牌。我还没有找到任何从刷新令牌中获取访问令牌的例子。 我参考了[Google+API参考],但他们使用HTTP方法提到了它。2请用C#提供一些使用Google+API提供的方法的例子。

  • 对于带有PKCE的Oauth 2.1,官方示例Spring授权服务器默认返回一个access_token和id_token https://github . com/spring-projects/spring-authorization-server/tree/main/samples/default-authorization server endpoint/oauth2/token有没有可能

  • 我有一个具有域范围委托设置的服务帐户,我正在尝试使用该服务帐户创建新帐户(google api服务管理目录),然后向新创建的帐户添加一些预设日历(google api services日历)。 我在目录api方面没有任何问题。我必须使用服务帐户创建一个委派(管理)用户,所有目录api调用都工作正常。 然而,我在日历api调用工作时遇到了问题。 Java依赖性: Java代码: 堆栈跟踪 : 有趣的