How can I access group members with a service account?

2.7k views Asked by At

I am attempting to use a service account to access members of a group. I have verified that I can do this using a normal OAuth2 token on behalf of a user, with a call to https://www.googleapis.com/admin/directory/v1/groups/{group}/members and the scope https://www.googleapis.com/auth/admin.directory.group.readonly.

I’d like to do the same with a service account, and I have added the service account email address as a group member and verified that View Members permissions are set to “All members of the group, All organization members”.

When I ask for a list of members, I receive this error:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Not Authorized to access this resource/api"
   }
  ],
  "code": 403,
  "message": "Not Authorized to access this resource/api"
 }
}

What do I need to do to authorize this service account to see the group?

2

There are 2 answers

5
omerio On

You can follow the steps outlined in the following API docs page to create the service account and perform a domain wide delegation of authority, please bear in mind you need the email address of any user who is a member of the group (userEmail in the code snippet below) so the service account can act on their behalf:

https://developers.google.com/admin-sdk/directory/v1/guides/delegation

The page includes a Java and Python examples of how to instantiate a com.google.api.services.admin.directory.Directory object using the service account and private key created on the Google Developers Console

 GoogleCredential credential = new GoogleCredential.Builder()
  .setTransport(httpTransport)
  .setJsonFactory(jsonFactory)
  .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
  .setServiceAccountScopes(DirectoryScopes.ADMIN_DIRECTORY_USERS)
  .setServiceAccountUser(userEmail)
  .setServiceAccountPrivateKeyFromP12File(
      new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
  .build();
0
Abhishek Mishra On

Assume that you have the following

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ["https://www.googleapis.com/auth/admin.directory.user", 
          "https://www.googleapis.com/auth/admin.directory.group"]

credentials = service_account.Credentials.from_service_account_file(
                PATH-TO-YOUR-SERVICE-ACCOUNT-FILE, 
                scopes=SCOPES, subject=ADMIN-EMAIL-ID)
service = build('admin', 'directory_v1', credentials=credentials)
group = "YOUR-GROUP-EMAIL-ID"
direct_members = service.members().list(groupKey=group).execute()["members"]
print(direct_members)

# Note that the above code would give only direct members.
# To get the direct members, set the `inclueDerivedMembership` 
# argument to True as below.
all_members = service.members().list(
              groupKey=group, inclueDerivedMembership=True).execute()["members"]
print(all_members)

The source of truth of this answer is here.