Gleko
Gleko

Reputation: 127

Getting "Error: Not Authorized to access this resource/api" when trying to create google groups through Firebase functions

I am trying to create a unique google group every time a new entry is created in the firestore database using google admin api within firebase functions.

The onCreate function within the functions index.js therefore call the following function to create the group:

async function createSupplierOrderChannel(orderId, supplierId, customerEmail, supplierEmail) {
  const auth = new google.auth.GoogleAuth({
      scopes: [
        'https://www.googleapis.com/auth/admin.directory.group',
        'https://www.googleapis.com/auth/admin.directory.user',
        'https://www.googleapis.com/auth/admin.directory.group.member'
      ]
  });
  
  const client = await auth.getClient();
  console.log('Service Account Email:', await auth.getCredentials());
  const googleAdmin = google.admin({
      version: 'directory_v1',
      auth: client
  });
  
  const groupEmail = `order-${orderId}-supplier-${supplierId}@${GOOGLE_WORKSPACE_DOMAIN}`;
  
  // Create Google Group
  await googleAdmin.groups.insert({
      requestBody: {
          email: groupEmail,
          name: `Order ${orderId} - Supplier ${supplierId}`,
          description: `Communication channel for order ${orderId} with supplier ${supplierId}`
      }
  });
  
  return groupEmail;
}

As can be seen, for sanity check I am printing out the service account email that is used to make this call, which is the firebase service account with the following format:

[email protected]

Having searched around, I have added the following scopes to this client id in domain wide delegation:

https://www.googleapis.com/auth/admin.directory.group.member
https://www.googleapis.com/auth/admin.directory.user
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.user.security

For some reason, running the function results in the following error in the function logs:

Error: Not Authorized to access this resource/api

What permission am I missing?

Upvotes: 0

Views: 33

Answers (1)

Gleko
Gleko

Reputation: 127

Figure it out. In addition to the scope you have to also provide the credential json file that is obtained from the google admin console service account page as well as the subject that is being impersonated. The whole section therefore becomes:

const auth = new google.auth.GoogleAuth({
      keyFile: './your-credentials-file.json',
      scopes: [
        'https://www.googleapis.com/auth/admin.directory.group',
        'https://www.googleapis.com/auth/admin.directory.user',
        'https://www.googleapis.com/auth/admin.directory.group.member'
      ],
      clientOptions: {
        subject: '[email protected]'
      }

Upvotes: 0

Related Questions