在App Engine上使用Google Application Default Credentials时出错

all*_*tta 5 google-app-engine google-api google-authentication google-oauth

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

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 */
        }
      })
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误: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.

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

Tym*_*ack 0

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

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);
}
Run Code Online (Sandbox Code Playgroud)