Error when using Google Application Default Credentials on App Engine

Viewed 690

I am trying to make a Node.js app (running Express on App Engine) authenticate with Google API (Server-to-Server) using the Google Application Default Credentials. The app is supposed to use the credentials to talk with Google Analytics, which I have set up by turning on the Analytics API in the Google Developers Console. This is the code I have implemented:

var google = require('googleapis')
var analytics = google.analytics('v3')

app.post('/getAnalyticsData', (req, res) => {
  google.auth.getApplicationDefault(function(err, authClient) {
    if (err) {
      /* Handle error */
    }
    if (authClient) {
      if (authClient.createScopedRequired && authClient.createScopedRequired()) {
        authClient = authClient.createScoped(['https://www.googleapis.com/auth/analytics.readonly'])
      }
      analytics.data.ga.get({
        'auth': authClient,
        'ids': 'ga:VIEW_ID',
        'metrics': 'ga:pageviews,ga:sessions',
        'start-date': '2017-01-01',
        'end-date': '2017-03-09'
      }, function(err, response) {
        if (err) {
          console.log("Analytics error: ", err)
        }
        if (response) {
          console.log("YAY! Analytics response: ", response)
          /* Do something with the response */
        }
      })
    }
  })
})

But I am getting this error: A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified. Insufficient Permission.

Any idea how to solve this and succeed with the authentication?

1 Answers

I had the same error when trying to use google-auth-library to connect to datastore and was unable to set the correct permissions for the default service account. I found an example in their samples folder that created an auth client using a key file. You can create your own service account with the right permissions and generate a key file on the service account admin page in the cloud console. Hope this helps.

const {auth} = require('google-auth-library');

async function getDnsInfo() {
  const client = await auth.getClient({
    keyFile: 'path/to/keyFile.json,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
  });
  const projectId = await auth.getProjectId();
  const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({url});
  console.log('DNS Info:');
  console.log(res.data);
}
Related