Is it possible to authorize admin service with another user credential?
Answer:
Assuming that this other user does not have admin privileges, your only option would be to use a service account with domain-wide delegation that impersonates your admin account:
- Perform Google Workspace Domain-Wide Delegation of Authority
Workflow:
- Create a service account.
- Follow this guide to grant the service account domain-wide delegation, so that it can be used to impersonate any account in your domain: in this case, your account.
- Import and use the library OAuth2 for Apps Script in order to use the service account in your Apps Script project.
- Use UrlFetchApp to call your desired API, using the access token from the service account.
Code sample:
For example, if you wanted to call Directory API's users.get to retrieve data from the user currently executing this, you would do something like this:
function getService() {
const service = OAuth2.createService("Service account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
.setIssuer(SERVICE_ACCOUNT_EMAIL)
.setSubject(IMPERSONATED_EMAIL)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/admin.directory.user')
return service;
}
function getActiveUserData() {
const service = getService();
if (service.hasAccess()) {
const userKey = Session.getActiveUser();
const url = `https://admin.googleapis.com/admin/directory/v1/users/${userKey}`;
const options = {
headers: {
'Authorization': "Bearer " + service.getAccessToken(),
'Content-Type': 'application/json'
},
muteHttpExceptions: true
}
const resp = UrlFetchApp.fetch(url, options);
const userData = JSON.parse(resp.getContentText());
return userData;
}
}