2

我可以在客户端应用程序中使用服务帐户访问 Google Analytics 数据吗?如果没有,是否有其他方法可以达到相同的结果?

必须完全是客户端,并且不得要求用户进行身份验证(因此需要使用服务帐户)。

4

2 回答 2

3

是的,您可以在https://code.google.com/apis/console中确保您说它是一个服务帐户,它将为您提供一个可供下载的密钥文件。这样您就不需要用户单击确定来授予您访问权限。

要使服务帐户正常工作,您需要有一个密钥文件。任何有权访问该密钥文件的人都可以访问您的 Analytics 数据。Javascript 是客户端的,这意味着您需要发送密钥文件。看到问题了吗?您正在让每个人都可以访问您的帐户。即使出于安全原因您可以使用 javascript 获得服务帐户,这也可能不是一个好主意。

于 2013-08-28T07:15:26.970 回答
1

您可以使用 Node.js 的官方(和 alpha)Google API 来生成令牌。如果您有服务帐户,这将很有帮助。

在服务器上:

npm install -S googleapis

ES6:

import google from 'googleapis'
import googleServiceAccountKey from '/path/to/private/google-service-account-private-key.json' // see docs on how to generate a service account

const googleJWTClient = new google.auth.JWT(
  googleServiceAccountKey.client_email,
  null,
  googleServiceAccountKey.private_key,
  ['https://www.googleapis.com/auth/analytics.readonly'], // You may need to specify scopes other than analytics
  null,
)

googleJWTClient.authorize((error, access_token) => {
   if (error) {
      return console.error("Couldn't get access token", e)
   }
   // ... access_token ready to use to fetch data and return to client
   // even serve access_token back to client for use in `gapi.analytics.auth.authorize`
})

如果您使用“将 access_token 传递回客户端”路线:

gapi.analytics.auth.authorize({
  'serverAuth': {
    access_token // received from server, through Ajax request
  }
})
于 2017-04-13T20:47:48.773 回答