I saw so many question relating to this GCP issue, none of it helped. I have created service account and added to "Manage Domain-wide delegation" with scopes. But I still get this error Client is unauthorized to retrieve access tokens using this method or client not authorized for any of the scopes requested.
code is below:
from google.oauth2 import service_account
SCOPES = [
"https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/admin.directory.domain.readonly",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.send",
"https://www.googleapis.com/auth/gmail.insert",
"https://www.googleapis.com/auth/gmail.settings.sharing",
]
SERVICE_ACCOUNT_FILE = '/PATH/TO/FILE/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES, )
delegated_credentials = credentials.with_subject('email')
service = build('admin', 'directory_v1', credentials=delegated_credentials)
def main():
print("Getting the first 10 users in the domain")
results = (
service.users()
.list(customer="customer_id", maxResults=10, orderBy="email")
.execute()
)
users = results.get("users", [])
print(users)
Delegation means impersonating another identity. What permissions does the identity in this line of code have credentials.with_subject('email')
? The identity needs super administrator access to the relevant Google Workspace account
.
Additionally, the user must have logged in at least once and accepted the Google Workspace Terms of Service.