在App Engine

时间:2017-11-21 13:09:49

标签: google-app-engine google-api google-oauth google-authentication

我正在尝试使用Google Application Default Credentials使用Google API(服务器到服务器)对Node.js应用程序(在App Engine上运行Express)进行身份验证。该应用应该使用凭据与Google Analytics进行对话,我通过启用Analytics API中的Google Developers Console来设置该Google Analytics。这是我实施的代码:

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 */
        }
      })
    }
  })
})

但我收到此错误: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

知道如何解决这个问题并通过身份验证取得成功吗?

1 个答案:

答案 0 :(得分:0)

当我尝试使用google-auth-library连接到数据存储时遇到相同的错误,并且无法为默认服务帐户设置正确的权限。我在他们的示例文件夹中找到一个example,该文件夹使用密钥文件创建了auth客户端。您可以使用适当的权限创建自己的服务帐户,并在云控制台的service account admin page上生成密钥文件。希望这会有所帮助。

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);
}