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": "",
    "client_id": "1234567890",
    "user_email": ""

function getOAuthService(user) {
    return OAuth2.createService("Service Account")
        .setParam('access_type', 'offline')

function getUserFiles() {
    var service = getOAuthService();
    if (service.hasAccess()) {
        var url = '';
        var response = UrlFetchApp.fetch(url, {
            headers: {
                Authorization: 'Bearer ' + service.getAccessToken()

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

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.