问题
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)
回答1:
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")
来源:https://stackoverflow.com/questions/60262432/service-account-not-authorized-to-access-this-resource-api-while-trying-to-acces