I'm encountering an issue while attempting to access user data using the Google Admin SDK Directory API with a service account. Here's the scenario:
I have a Python script that utilizes the Google Admin SDK Directory API to retrieve user data. I'm using a service account to authenticate the API requests. I've followed the steps outlined in the Google documentation to set up domain-wide delegation, and I've granted the necessary permissions to the service account, including the "User Management Admin" role. When I attempt to retrieve user data for non-admin users, I receive a 403 error with the message "Not Authorized to access this resource/api". Here's a simplified version of my Python script:
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Replace 'path/to/your/service-account-key.json' with the path to your service account key file
SERVICE_ACCOUNT_KEY_FILE = 'path/to/your/service-account-key.json'
# Replace '[email protected]' with the email address you want to check
USER_EMAIL_TO_CHECK = '[email protected]'
# Load service account credentials
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_KEY_FILE,
scopes=['https://www.googleapis.com/auth/admin.directory.user.readonly'],
)
# Impersonate the user
credentials = credentials.with_subject(USER_EMAIL_TO_CHECK)
# Build the Admin SDK Directory API client
directory_service = build('admin', 'directory_v1', credentials=credentials)
try:
# Retrieve user information
user = directory_service.users().get(userKey=USER_EMAIL_TO_CHECK).execute()
print(user)
# If the user exists, print their information
print(f'User exists in Active Directory: {user["primaryEmail"]}')
except Exception as e:
# If an exception occurs, the user does not exist
print(f'User does not exist in Active Directory: {USER_EMAIL_TO_CHECK}')
print(f'Error: {e}')
I've verified that the service account is correctly set up with domain-wide delegation and has the necessary permissions. I've also ensured that the user I'm trying to impersonate exists in the Active Directory.
Can anyone provide insight into why I'm receiving a 403 error when attempting to access user data for non-admin users using the Google Admin SDK Directory API with a service account, despite having set up domain-wide delegation and granting the necessary permissions? also I am getting details for the admin email id but getting 403 error for other emails in my workspace