Service account

This describes how to get an access token from the Goa library using a service account, as described in Oauth2 for Apps Script in a few lines of code (which you should read first for background).

If you have initialized the credentials as described in Goa Setup, this is good to go. There is no consent dialog required for a service account.

This example does a query using the Google DataStore API and a service account flow.

getting the token

function dataStoreSA (params) {
       
  // pick up the token refreshing if necessary
  var goa = cGoa.GoaApp.createGoa('DriverDatastore_serviceaccount', PropertiesService.getScriptProperties()).execute(params);
  
  if (!goa.hasToken()) {
    throw 'no token retrieved';
  }
  
  // do a test - passing the token and any parameters that arrived to this function
  Logger.log (testDataStore (goa.getToken(), goa.getParams(params) ));
  

consuming the token

function testDataStore (accessToken,params) {
 
   var options = {
     method: "POST",
     contentType : "application/json" ,
     muteHttpExceptions : true,
     headers: {
       "authorization": "Bearer " + accessToken,
     },
     payload:JSON.stringify({
       "query": {
        "kinds": [{"name":"polymerdbab"}]
       }
      })
   };
   

  return UrlFetchApp.fetch( 
    "https://www.googleapis.com/datastore/v1beta2/datasets/xliberationdatastore/runQuery", options);

}

Using a service account service.

When the service account one off credentials package is created, it uses the data from the JSON file, as in this example.

 cGoa.GoaApp.setPackage (propertyStore , cGoa.GoaApp.createServiceAccount (DriveApp , {

    packageName: 'DriverDatastore_serviceaccount',

    fileId:'0B9xxxxxxx2s',

    scopes : cGoa.GoaApp.scopesGoogleExpand (['datastore','userinfo.email']),

    service:'google_service'

  }));


Notice the use of the service definition 'google_service', which looks like this.

google_service: {
  authUrl: "https://www.googleapis.com/oauth2/v3/token",
  tokenUrl: "https://www.googleapis.com/oauth2/v3/token",
  defaultDuration: 600,
  accountType: "serviceaccount"
}


For more like this, see OAuth2 for Apps Script in a few lines of code Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, All formats are available from O'ReillyAmazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.


Comments