Google Cloud Function Admin SDK Integration
If you’re building enterprise software on Google Cloud Functions and need to interface with Google Workspace (formerly G Suite), the Google Admin SDK is often essential. For instance, you might need to fetch and manage all users in your organization. However, Google doesn’t provide a native, one-click integration for the Admin SDK in Cloud Functions. Furthermore, I was surprised that I couldn’t find a simple article on how to set this up. In this guide, we’ll walk through how to configure your Cloud Function so that it can access Google Admin SDK APIs (including those that require admin privileges).
Step-by-Step Guide
1. Create a Google Cloud or Firebase Project
- Navigate to the Google Cloud Console (or Firebase Console).
- Create a new project or use an existing one.
This project will house your Cloud Function and the relevant APIs you’ll enable.
2. Create a Service Account
- In the Google Cloud Console, go to IAM & Admin > Service accounts.
- Click Create service account and fill out the details.
- Click Create and then Continue.
A service account is essentially a technical user that your code will use to call Google APIs.
3. Grant Your Service Account Access to the Google Admin SDK
- On the same service account page, under Grant this service account access to the project, give your service account the roles it needs. For the Admin SDK, typically you’ll enable the Service Account Token Creator role and make sure you have Google Admin SDK API enabled for your project.
- Enable the Admin SDK API in APIs & Services > Library by searching for “Admin SDK” and clicking Enable.
4. Download the Service Account Credentials
- In the service account list, find your newly created account.
- Under Actions, click Create key.
- Select JSON and download the credential file.
Important: Never commit this JSON file to source control or otherwise expose it publicly. Use the Secret Manager to store your secret and map it into your function.
5. Set Up Your Cloud Function
You have two main options:
- Use the Google Cloud Console (or Firebase Console) inline editor.
- Deploy via a local development environment with the gcloud CLI.
Wherever you’re coding, make sure you have a way to reference your service account JSON file.
6. Install the Node.js Google API Client
Within your function’s directory (or via the console editor), install the googleapis package:
npm install googleapis
This library is your gateway to all Google APIs, including Admin SDK, Drive API, etc.
7. Configure Authentication in Your Cloud Function
In your Node.js code, initialize the `googleapis` client using your service account credentials. An example snippet might look like this:
const { google } = require(‘googleapis’);
const path = require(‘path’);
exports.myAdminFunction = async (req, res) => {
try {
const auth = new google.auth.GoogleAuth({
keyFile: path.join(__dirname, ‘path-to-your-service-account.json’),
scopes: [
// Provide the exact scopes your API needs, e.g.:
‘https://www.googleapis.com/auth/admin.directory.user.readonly',
// Add more if needed
],
});
const authClient = await auth.getClient();
// Now you can create an instance of, for example, the Admin SDK
const admin = google.admin({ version: ‘directory_v1’, auth: authClient });
// Example: List users
const response = await admin.users.list({
customer: ‘my_customer’,
maxResults: 10,
orderBy: ‘email’,
});
res.status(200).send(response.data);
} catch (err) {
console.error(err);
res.status(500).send(‘Error fetching users’);
}
};
8. Manage Service Account Credentials Securely with Secret Manager
Rather than deploying your service account JSON file with your function, use Google Cloud’s Secret Manager to store and mount your credentials securely:
Store Your Service Account Key:
Upload your service account JSON file as a secret via the Cloud Console or using the gcloud CLI:
gcloud secrets create SERVICE_ACCOUNT_KEY — data-file=path/to/your-service-account.json
Ensure that only your Cloud Function’s service account has permission to access this secret.
Mount the Secret into Your Cloud Function:
For Cloud Functions (2nd gen or later), you can mount secrets as files or environment variables. We are mountaing it is file. To do so, deploy your function with:
gcloud functions deploy myAdminFunction \
— runtime nodejs18 \
— trigger-http \
— set-secrets=SERVICE_ACCOUNT_KEY=/secrets/SERVICE_ACCOUNT_KEY:latest
This command mounts the latest version of your secret to /secrets/SERVICE_ACCOUNT_KEY in your function’s file system.
Update Your Code for Production:
Modify your code to reference the mounted file path instead of a locally stored JSON file:
const { google } = require(‘googleapis’);
const path = require(‘path’);
exports.myAdminFunction = async (req, res) => {
try {
const auth = new google.auth.GoogleAuth({
keyFile: path.join(‘/secrets’, ‘SERVICE_ACCOUNT_KEY’),
scopes: [
‘https://www.googleapis.com/auth/admin.directory.user.readonly',
],
});
const authClient = await auth.getClient();
const admin = google.admin({ version: ‘directory_v1’, auth: authClient });
const response = await admin.users.list({
customer: ‘my_customer’,
maxResults: 10,
orderBy: ‘email’,
});
res.status(200).send(response.data);
} catch (err) {
console.error(err);
res.status(500).send(‘Error fetching users’);
}
};
Using Secret Manager ensures your sensitive credentials remain secure and are centrally managed, reducing the risk of exposure.
Note: Use an environment variable for the path to the secret to support different environments like local, dev, or production.
9. Define the Correct Scopes
Each API requires specific scopes. Reference this list of scopes to add only what you need. Overly broad scopes might cause security issues or require unnecessary permissions.
For example, if you only need to read users from the Admin directory, use:
https://www.googleapis.com/auth/admin.directory.user.readonly
10. Domain-Wide Delegation for Admin-Only APIs
Many Admin SDK APIs require admin privileges in your Google Workspace. To enable your service account to act on behalf of an admin, you must configure domain-wide delegation.
- Log in to Google Workspace with an admin account.
- Go to: Security -> API controls -> Domain-wide delegation.
- Click: Add new (or Manage Domain Wide Delegation).
- Add your service account’s Client ID.
- In OAuth Scopes, enter the exact scopes your application needs (e.g. https://www.googleapis.com/auth/admin.directory.user).
Without domain-wide delegation, your service account will not be able to call Admin SDK endpoints that require admin privileges.
11. Impersonating an Admin User
Even after granting domain-wide delegation, you still need to specify which admin user you want to impersonate in your code. Do this by setting the subject property in your GoogleAuth configuration:
const auth = new google.auth.GoogleAuth({
keyFile: path.join(__dirname, ‘path-to-your-service-account.json’),
scopes: [
‘https://www.googleapis.com/auth/admin.directory.user',
// … other scopes …
],
clientOptions: {
subject: ‘admin-user@yourdomain.com’, // The admin you want to impersonate
},
});
When this service account authenticates, it will “act as” that admin user, allowing it to access the Admin SDK’s privileged APIs.
12. Deploy and Test
Once your code is ready and your domain-wide delegation is set up:
- Deploy your function to Google Cloud or Firebase and your Service Account to the Secrete Manager
- Test the function by making an HTTP request (if it’s an HTTP-triggered function) or triggering it via its designated trigger.
If everything is configured correctly, you should be able to fetch your users from the Admin SDK (or perform other admin-level actions you’ve authorized).
Conclusion
While it’s unfortunate that there isn’t a ready-made, one-click solution for integrating Admin SDK in Google Cloud Functions, you can still achieve it with the above steps. The key is configuring domain-wide delegation and impersonating an admin user. With these configurations, your service account can act on behalf of your admin, giving you programmatic access to manage your users, groups, and more.
Key Takeaways:
- Always keep your service account JSON secure — never check it into source control.
- Use domain-wide delegation for admin-specific SDK calls.
- Specify `clientOptions.subject` to impersonate an admin user.
Now you can build enterprise-grade solutions that manage Google Workspace resources, all running on serverless Cloud Functions. Enjoy your newfound control over your organization’s resources! If you need any help or consulting with the GCP, just reach out to me.