【问题标题】:Service account not Authorized to access this resource/api while trying to access directory api using Python尝试使用 Python 访问目录 api 时,服务帐户未授权访问此资源/api
【发布时间】:2020-06-01 09:13:31
【问题描述】:

我们使用 Python 从特定 G Suite 托管域中获取所有用户,但是在完成以下 tutorial 并授予服务帐户所需的所有访问权限后,以下 sn-p 仍然会产生“未授权访问此资源/api:

import json
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']

credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES)

service = build('admin', 'directory_v1', credentials=credentials)

【问题讨论】:

    标签: google-cloud-platform google-workspace google-directory-api


    【解决方案1】:

    Google documentation 中有一个(非常模糊的)线索来解决这个问题:

    注意:只有有权访问 Admin API 的用户才能访问 Admin SDK 目录 API,因此您的服务帐户需要模拟 其中一位用户可以访问 Admin SDK Directory API。 此外,用户必须至少登录一次并接受 G Suite 服务条款。

    在 Python 中实现模拟的方法是在使用 OAuth2 库进行身份验证时发送一个“主题”。主题应该是有权访问 Admin API 的用户(他不必是管理员,用户管理角色应该足够了,至少满足我的需要)。

    一个工作的 sn-p:

    import json
    from google.oauth2 import service_account
    from googleapiclient.discovery import build
    
    SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
    
    credentials = service_account.Credentials.from_service_account_file("/path/to/file.json", scopes=SCOPES, subject="admin@yourdomain.com")
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2013-09-13
      • 2021-03-29
      • 1970-01-01
      • 2018-05-16
      • 2016-12-24
      • 2021-10-30
      • 2019-04-16
      • 2020-01-06
      相关资源
      最近更新 更多