Cen*_*noc 10 oauth google-analytics-api oauth-2.0 google-oauth
我有一个全局帐户,有几个视图,我想在服务器端使用嵌入仪表板为客户端的各种视图.根据我的理解,我在服务器端使用服务帐户获取访问令牌,然后可以在需要时将访问令牌发送到客户端.我在想,这是正确的流程吗?访问令牌应该是每个会话吗?
此处显示的客户端授权有一个服务器身份验证访问令牌字段,但找不到我想要的确切流量的文档.基本上我不确定生成该服务器身份验证访问令牌的正确方法是什么.任何帮助/指针将非常感激.
[此处][1] 是如何设置服务器端身份验证的示例。当任何人访问该网站时,上面的代码都会创建一个新令牌。您可以在[此处][2]查看获取该访问令牌的端点。
以下是获得工作版本的一般步骤:
第 1 步:创建服务帐户并下载 JSON 密钥
第 2 步:将服务帐户添加为 Google Analytics 中的用户
步骤 3:使用 JSON 密钥数据请求访问令牌
# service-account.py
import json
from oauth2client.client import SignedJwtAssertionCredentials
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'
# Load the key file's private data.
with open(KEY_FILEPATH) as key_file:
_key_data = json.load(key_file)
# Construct a credentials objects from the key data and OAuth2 scope.
_credentials = SignedJwtAssertionCredentials(
_key_data['client_email'], _key_data['private_key'], SCOPE)
# Defines a method to get an access token from the credentials object.
# The access token is automatically refreshed if it has expired.
def get_access_token():
return _credentials.get_access_token().access_token
Run Code Online (Sandbox Code Playgroud)
回到客户端:
第 4 步:加载嵌入 API 库。
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
Run Code Online (Sandbox Code Playgroud)
步骤 5:添加 HTML 容器来托管仪表板组件。
<div id="chart-1-container"></div>
<div id="chart-2-container"></div>
Run Code Online (Sandbox Code Playgroud)
第6步:编写仪表板代码。
使用步骤 3 中获取的访问令牌对 Embed API 进行授权。
gapi.analytics.ready(function() { /** * 使用服务器端获取的访问令牌对用户进行授权。 */ gapi.analytics.auth.authorize({ 'serverAuth': { 'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT } }' } }); ...创建返回令牌的端点的额外工作取决于您的后端实现,但可以在[此处][2]找到演示如何实现的源代码。[1]: https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/ [2]:https://github.com/googleanalytics/ga-dev-tools/blob/abb3c5a18160327a38bf5c7f07437dc402569cac/lib/控制器/server_side_auth.py| 归档时间: |
|
| 查看次数: |
1624 次 |
| 最近记录: |