Google Directory API - Service acount with Domain-wide delegation

Hello everyone!

I’m trying to connect to the Google Directory API (REST Resource: users) via Airflow. I want to get a list of users within the organizational google workspace as well as update some attributes.

I want to do this programmatically via the service account that has been setup within the API project with appropriate scope:
https://www.googleapis.com/auth/admin.directory.user. The domain-wide delegation has also been enabled as well as the admin sdk api. The service account also has full permissions to the API project.

However, when I’m trying to run a basic standalone python script using google api client and google oauth2 to test if the service account is able to access the api and get a single user via their email, it’s throwing this error:
Error fetching user: <HttpError 403 when requesting https://admin.googleapis.com/admin/directory/v1/users/%40?alt=json returned “Not Authorized to access this resource/api”. Details: “[{‘message’: ‘Not Authorized to access this resource/api’, ‘domain’: ‘global’, ‘reason’: ‘forbidden’}]”>

However, when i add the email of the super admin for the impersonation, the service account is able to access the user in the directory api.

What is the reason? Am I missing something?

Thank you!

Hi - this is a common pitfall I’ve seen when using service accounts. When you setup domain-wide delegated access you are authorizing a service account to access data on behalf of a user. As the Directory API can return sensitive information you have to impersonate an account which has been assigned the Admin API privilege https://support.google.com/a/answer/1219251?sjid=11331467017520443782-EU#api&zippy=%2Cadmin-api (doesn’t have to be a super admin, just any account that has this privilege).

An alternative approach is assign an admin role to a service account https://support.google.com/a/answer/9807615?hl=en#zippy=%2Cassign-a-role-to-a-service-account. This approach also lets you grant the service account the appropriate role based on its needs e.g. Admin API privileges > Users > Read for read only actions

HTH

Martin

3 Likes