Home > front end >  Is it possible to authorize admin service with another user credential?
Is it possible to authorize admin service with another user credential?

Time:01-13

I would like to write an add-on to GMail via app script that would display some admin directory data.

But I want this add-on to work on a different account than my admin account. For example, I daily use my [email protected] to check emails, and from time to time I use my [email protected] account to manage admin stuff.

Is there a way to use the admin service as [email protected] while being logged as [email protected]?

CodePudding user response:

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:

Workflow:

  1. Create a service account.
  2. 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.
  3. Import and use the library OAuth2 for Apps Script in order to use the service account in your Apps Script project.
  4. 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;
  }
}
  •  Tags:  
  • Related