Setting up the Groups API

This page explains how to set up the Cloud Identity Groups API.

Before you begin

Enable the Cloud Identity API.

Enable the API

Installing the client libraries

To install the client libraries, run the following command:

Python

For more on setting up your Python development environment, refer to the Python Development Environment Setup Guide.

pip install --upgrade google-api-python-client google-auth \
  google-auth-oauthlib google-auth-httplib2

Authenticating with the Groups API

You can authenticate with the Groups API as an end user, as a service account group admin without domain-wide delegation, or as a service account with domain-wide delegation. The following sections describe each method.

Authenticating as an end user

If you're not an administrator, or are building an app that acts on behalf of users who aren't administrators, see Using OAuth 2.0 for web server applications, and then see the Instantiating a client section below.

Authenticating as a service account without domain-wide delegation

If you're using a service account and want to use it to manage groups as a group admin, complete the steps below. This authentication method should be used when you want the service account's actions to be registered in the audit logs as the service account.

Assigning an admin role to the service account

Tip: If the service account doesn't need access to all of the groups, consider making it an owner of the groups of interest. You don't need to assign the group admin role in this case.

First, you should assign the Google Workspace Group Administrator Role (Group Administrator) to the service account you want to delegate to, using the Admin SDK Roles and Role Assignments API. This step gives the service account access to the groups of the domain but no other resource.

See the Managing Roles guide for general information about managing Roles using the Admin SDK API. Follow the steps below to assign the Group Adminstrator role for your service account.

  1. From the developer console, select IAM & Admin > Service Accounts and click on the service account you want to use with the Groups API.

  2. Copy the Unique ID of the service account.

  3. Call the Admin SDK Roles API to identify the roleID for Group Administrator. You can use the API Explorer in the Admin SDK documentation to do this.

  4. Call the Role Assignments API with the following request body:

    {
      "assignedTo": "SERVICE_ACCOUNT_UNIQUE_ID"
      "roleID": "ROLE_ID"
      "scopeType": "CUSTOMER"
    }
    

Authenticating and authorizing the service account

You now have a service account with the Group Administrator role. The second step is to complete the OAuth authentication process for the service account.

  • If you are developing an app on Google Cloud and the service account is an owner of the project, you can use the application default credentials instead, which can simplify the process. See Authenticating as a Service Account for more information.

  • If the service account is not the owner of the project, follow the instructions below.

In either case, the applicable scope for the Cloud Identity Groups API is https://www.googleapis.com/auth/cloud-identity.groups.

  1. Using the credential you just created, generate an access token.

    Java

    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(emailAddress)
        .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
        .setServiceAccountScopes(ImmutableList.of("https://www.googleapis.com/auth/cloud-identity.groups"))
        .build();
    

    Keep the access token that's generated.

Full code for generating an access token for a service account

Java

GenerateServiceAccountOauth2Token.java

package com.google.tools;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.ImmutableList;
import java.io.FileInputStream;

/** Command line tool to generate Oauth2 token for a given service account 
/** without domain wide delegation. */
public final class GenerateServiceAccountOauth2Token {

  private static final ImmutableList<String> API_SCOPES =
      ImmutableList.of(
          "https://www.googleapis.com/auth/cloud-identity.groups",
          "https://www.googleapis.com/auth/admin.directory.group",
          "https://www.googleapis.com/auth/admin.directory.group.member",
          "https://www.googleapis.com/auth/apps.groups.settings");

  public static void main(final String[] args) throws Exception {
    String accessToken = getTokenFromJsonKey();
    System.out.println("Token: " + accessToken);
  }

  private static String getTokenFromJsonKey() throws Exception {
    GoogleCredential credential =
        GoogleCredential.fromStream(
            new FileInputStream(
                "<path for json file>"),
            new NetHttpTransport(),
            new JacksonFactory());
    System.out.println("ServiceAccountId=" + credential.getServiceAccountId());

    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    GoogleCredential.Builder builder =
        new GoogleCredential.Builder()
            .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
            .setServiceAccountPrivateKeyId(credential.getServiceAccountPrivateKeyId())
            .setServiceAccountId(credential.getServiceAccountId())
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountScopes(API_SCOPES)
            .setClock(credential.getClock());
    credential = builder.build();
    if (!credential.refreshToken()) {
      throw new Exception("Failed to fetch access token.");
    }
    return credential.getAccessToken();
  }
}

Build rule

java_binary(
  name = "generate_oauth2_token",
  srcs = ["GenerateServiceAccountOauth2Token.java"],
  main_class = "com.google.tools.GenerateServiceAccountOauth2Token",
  deps = [
      "//java/com/google/api/client/googleapis/auth/oauth2",
      "//java/com/google/api/client/googleapis/javanet",
      "//java/com/google/api/client/http",
      "//java/com/google/api/client/http/javanet",
      "//java/com/google/api/client/json",
      "//java/com/google/api/client/json/jackson2",
      "//java/com/google/common/base",
      "//java/com/google/common/collect",
  ],
)

Testing the service account

  1. Try any Groups API call with the service account credentials: create a group, add users, update group settings, etc.

  2. Check the Audit Logs in the Google Admin Console Reports section. You should see the service account as the actor for your group-related changes. See Log events for more information.

    Alternatively, you can use APIs to access audit logs. To check using the Reports API explorer, make sure to use your admin OAuth credentials.

Authenticating as a service account with domain-wide delegation

If you're an administrator managing identity groups, or if you want to provide an account with domain-wide privileges so it can manage Google Groups on behalf of admins, you should authenticate as a service account and then grant it the domain-wide privileges.

Follow the steps below to authenticate the service account and set up domain-wide delegation.

  1. Authenticate as a service account; refer to Using OAuth 2.0 for server to server applications. Then follow the steps below to

  2. Go to the Service Accounts page in the Cloud Console.

    Go to the Service Accounts page

  3. Click Select a project, choose a project, and click Open.

  4. Select your service account, and then click Edit.

  5. Click Show Domain-wide Delegation.

  6. Select Enable Google Workspace Domain-wide Delegation.

  7. Click Save.

Next, when initializing the credential in your code, specify the email address on which the service account acts by calling with_subject() on the credential. For example:

Python

credentials = service_account.Credentials.from_service_account_file(
  SERVICE_ACCOUNT_FILE, scopes=SCOPES).with_subject(delegated_email)

Instantiating a client

The following example shows how to instantiate a client using service account credentials. To authenticate as an end-user instead, replace the credential object from the service account with the credential you obtained earlier in Using OAuth 2.0 for web server applications.

Python

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/cloud-identity.groups']
SERVICE_ACCOUNT_FILE = '/path/to/service-account-file.json'

def create_service():
  credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
  delegated_credentials = credentials.with_subject('user@example.org')

  service_name = 'cloudidentity.googleapis.com'
  api_version = 'v1'
  discovery_url = (
    'https://%s/$discovery/rest?version=%s' % (service_name, api_version))
  service = googleapiclient.discovery.build(
    service_name,
    api_version,
    discoveryServiceUrl=discovery_url,
    credentials=credentials)

  return service

You can now begin making calls to the Groups API.