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

1

5

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 Account, the following snippet still produces "Not Authorized to access this resource/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)
Henceforward answered 17/2, 2020 at 12:25 Comment(0)
H
9

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="[email protected]")
Henceforward answered 17/2, 2020 at 12:25 Comment(3)
Can you please help what role should I give to subject , I searched but colud not found user management roleGamb
also how can I give access to admin apiGamb
O my god, I can sleep tonight! Using my workspace admin account/project owner email as subject worked. Why was this nowhere in the documentation???Grus

© 2022 - 2024 — McMap. All rights reserved.