gsuiteapi访问:客户端未经授权使用此方法检索访问令牌

2024-04-18 00:09:25 发布

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

我试图通过python脚本访问存储在googledrive中的文档。在

以下是我所做的:

  1. 创建了一个新的服务帐户并选择了“启用G套件域范围的委派”
  2. 然后,我为我的帐户进入GSuite admin,并通过Security->Advanced Settings->Manage API client access添加了为我的新服务帐户生成的客户端id和这些权限as detailed hereenter image description here

然后,我使用以下python方法来构建访问gsuite文档的服务:

def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    # credentials = ServiceAccountCredentials.from_json_keyfile_name(
    #         key_file_location, scopes=scopes)
    credentials = service_account.Credentials.from_service_account_file(
        key_file_location, scopes=scopes)

    delegated_credentials = credentials.with_subject('myemail@my-gsuite-domain.com')

    # Build the service object.
    service = build(api_name, api_version, credentials=delegated_credentials)

    return service

当我试图访问电子表格时,出现以下错误:

('unauthorized_client: Client is unauthorized to retrieve access tokens using this method.', u'{\n "error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method."\n}')

电子表格具有组织中任何人都可以查看的权限。在

我还尝试手动将服务帐户电子邮件地址添加到电子表格权限中,这样做允许我在不使用委派凭据的情况下访问文档,但我希望避免将电子邮件地址添加到我要访问的每个电子表格中。在

如何使用Python以编程方式查看组织成员可以查看的所有Google工作表?在

谢谢。在


Tags: thetokeyname文档apiversionservice
1条回答
网友
1楼 · 发布于 2024-04-18 00:09:25

谢谢你的指点。问题原来是请求作用域https://www.googleapis.com/auth/spreadsheets.readonly,而我只有一个授权的作用域https://www.googleapis.com/auth/spreadsheets。我以为spreadsheets是{}的超集,但事实并非如此。在

我的get_服务代码:

def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)
    # credentials = service_account.Credentials.from_service_account_file(
    #     key_file_location, scopes=scopes)

    delegated_credentials = credentials.create_delegated('name@example.com')  
    delegated_http = delegated_credentials.authorize(Http())

    # Build the service object.
    service = build(api_name, api_version, http=delegated_http)

    return service

以及我对get_service的呼叫:

^{pr2}$

相关问题 更多 >

    热门问题