Using Google Service Accounts with Google Apps Script

This sample code shows how to use OAuth in Google Apps Script using Service Accounts. The G Suite 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.