使用服务帐户访问Google AnalyticsAPI API

时间:2013-08-28 03:09:40

标签: javascript google-api oauth-2.0 google-analytics-api

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

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

2 个答案:

答案 0 :(得分:3)

是的,您可以在https://code.google.com/apis/console确保您说它是一个服务帐户,它会为您提供一个要下载的密钥文件。有了这个,你不需要用户点击确定给你访问。

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

答案 1 :(得分:0)

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

在服务器上:

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

如果你去了#34;将access_token传回客户端"路线:

gapi.analytics.auth.authorize({
  'serverAuth': {
    access_token // received from server, through Ajax request
  }
})
相关问题