Service account not Authorized to access this resource/api while trying to access directory api using Python

后端 未结 1 877
不知归路
不知归路 2020-12-20 02:15

We use Python to get all users from a particular G Suite managed domain, but after completing the following tutorial and granting all the access needed to the Service Accoun

相关标签:
1条回答
  • 2020-12-20 02:50

    There is a (very vague) clue in Google documentation to the solution:

    Note: Only users with access to the Admin APIs can access the Admin SDK Directory API, therefore your service account needs to impersonate one of those users to access the Admin SDK Directory API. Additionally, the user must have logged in at least once and accepted the G Suite Terms of Service.

    The way to achieve the impersonation in Python is by sending a "subject" when authenticating with OAuth2 library. The subject should be a user with an access to the Admin API (He doesn't have to be an admin, User Management Role should be sufficient, at least for my needs).

    A working snippet:

    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")
    
    0 讨论(0)
提交回复
热议问题