How to Use Google Service Accounts with Google Apps Script

This sample code shows how to use OAuth in Google Apps Script using Service Accounts. The Google Workspace admin can access the Google Drive files of any user - the username or email address of the user you are trying to impersonate specified with the method setSubject.

For this code to work, you need to create a Google Service account with domain-wide delegation, substitute the private key and client client email with the actual values and also add the Client Id to your Google Apps admin console with the Drive API Scope. The OAuth 2.0 access tokens are stored in the Script Properties.

var JSON = {
  private_key: 'Your Private Key',
  client_email: 'serviceacount@project-ctrlq.iam.gserviceaccount.com',
  client_id: '1234567890',
  user_email: 'amit@labnol.org',
};

function getOAuthService(user) {
  return OAuth2.createService('Service Account')
    .setTokenUrl('https://accounts.google.com/o/oauth2/token')
    .setPrivateKey(JSON.private_key)
    .setIssuer(JSON.client_email)
    .setSubject(JSON.user_email)
    .setPropertyStore(PropertiesService.getScriptProperties())
    .setParam('access_type', 'offline')
    .setScope('https://www.googleapis.com/auth/drive');
}

function getUserFiles() {
  var service = getOAuthService();
  service.reset();
  if (service.hasAccess()) {
    var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1';
    var response = UrlFetchApp.fetch(url, {
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken(),
      },
    });
    Logger.log(response.getContentText());
  }
}

function reset() {
  var service = getOAuthService();
  service.reset();
}

It is important to specify the user’s email on behalf of whom you wish to run this application else you’ll get a “Not Authorized to access this resource/api” error.

Also, if you are getting the 403 Insufficient permission error, it is likely because the application is request access to API scopes that are not authorized in the Google Apps admin console. The invalid_grant error is likely due to incorrect date and time settings of the server that is hosting the application.

Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

0

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.