如何获取Google服务帐户访问令牌javascript [英] How to obtain Google service account access token javascript

查看:654
本文介绍了如何获取Google服务帐户访问令牌javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置我网站的分析仪表板,以便我查看网站使用情况。我不希望他们必须拥有一个谷歌帐户或单独添加它们才能看到结果。

I'm trying to set up an analytics dashboard of my site for my leadership to view site usage. I don't want them to have to have a google account or to add them individual to see the results.

我已经设置了服务帐户和OAuth2访问权限。我找到的所有教程都显示如下代码:

I've set up a service account and OAuth2 access. All the tutorials I find show code like this:

gapi.analytics.auth.authorize({
  clientid: 'Service account client ID',
  serverAuth: {
      access_token: 'XXXXXXXXXXXXXXXXX'
}

并且所有文档都谈到......一旦你收到你的访问令牌......但他们中没有人真正说出如何获得它!我看到了证书指纹,公钥指纹。我也看到了如何生成JSON和P12密钥。我不知道如何生成访问令牌。

And all the documentation talks about "...once you recieve your access token...." But none of them actually say how to get that! I see Certificate Fingerprints, Public key fingerprints. I also see how to generate JSON and P12 keys. I don't see how to generate the access token.

有人可以解释如何执行此操作吗?

Can someone explain how to do this?

我发现这个。它解释说我需要密钥文件,这是一个坏主意,但没有说明如何实际做到这一点。

I found this. It explains that I need the key file and that it is a bad idea, but doesn't say how to actually do it.

我还发现这个 .B我对Node.js一无所知,我希望这只是一条可能的路线?

I also found this. But I don't know anything about Node.js and I'm hoping that is just one possible route?

推荐答案

终于得到了它工作!使用kjur的jsjws纯JWT的JavaScript实现。我使用此演示作为生成JWT以请求令牌的基础。以下是步骤

Finally got it working! Using kjur's jsjws pure JavaScript implementation of JWT. I used this demo as the basis for generating the JWT to request the token. Here are the steps

在Google Developers控制台中,我创建了一个服务帐户。以下是此说明

In the Google Developers console I created a service account. Here are instructions for that

在Google API控制台中,我将服务帐户添加到凭据中。然后我生成了一个新的JSON密钥。这为我提供了纯文本格式的私钥

In the Google API console I added the service account to the credentials. I then generated a new JSON key. This gives me my private key in plain text format.

然后我按照谷歌的说明使用HTTP / REST进行授权API调用。

I then followed these instructions from google on making an authorized API call using HTTP/REST.

这是必需的标题信息。

This is the required header information.

var pHeader = {"alg":"RS256","typ":"JWT"}
var sHeader = JSON.stringify(pHeader);

索赔集就是这样的。 (这是使用由上述KJUR JWT库提供的语法。)

And the claim set is something like this. (This is using syntax that is supplied by the KJUR JWT library described above.)

var pClaim = {};
pClaim.aud = "https://www.googleapis.com/oauth2/v3/token";
pClaim.scope = "https://www.googleapis.com/auth/analytics.readonly";
pClaim.iss = "<serviceAccountEmail@developer.gserviceaccount.com";
pClaim.exp = KJUR.jws.IntDate.get("now + 1hour");
pClaim.iat = KJUR.jws.IntDate.get("now");

var sClaim = JSON.stringify(pClaim);

有争议的一点是将我的私钥放入客户端代码中。对于这种用法并没有那么糟糕(我不这么认为。)首先,该网站是我们公司防火墙的后面,所以谁会破解它?其次,即使有人确实得到了它,服务帐户的唯一授权就是查看我们的分析数据 - 我的仪表板的目的是访问该页面的任何人都可以查看我们的分析数据。不打算在这里发布私钥,但基本上就是这样。

The the controversial bit is putting my private key into the client side code. For this usage it isn't that bad (I don't think.) First, the site is behind our corporate firewall, so who is going to "hack" it? Second, even if someone did get it, the service account's only authorization is to view our analytics data -- which is the purpose of my dashboard is that anybody who visits the page can view our analytics data. Not going to post the private key here, but basically like so.

var key = "-----BEGIN PRIVATE KEY-----\nMIIC....\n-----END PRIVATE KEY-----\n";`enter code here`

然后生成一个签名的JWT,其中

Then generated a signed JWT with

 var sJWS = KJUR.jws.JWS.sign(null, sHeader, sClaim, key);

之后我使用XMLHttpRequest来调用google API。我尝试将FormData与请求一起使用,但这不起作用。所以旧的(呃)学校

After that I used XMLHttpRequest to call the google API. I tried to use FormData with the request but that didn't work. So the old(er) school

var XHR = new XMLHttpRequest();
var urlEncodedData = "";
var urlEncodedDataPairs = [];

urlEncodedDataPairs.push(encodeURIComponent("grant_type") + '=' + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer"));
urlEncodedDataPairs.push(encodeURIComponent("assertion") + '=' + encodeURIComponent(sJWS));
urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');

// We define what will happen if the data are successfully sent
XHR.addEventListener('load', function(event) {
    var response = JSON.parse(XHR.responseText);
    token = response["access_token"]
});

// We define what will happen in case of error
XHR.addEventListener('error', function(event) {
    console.log('Oops! Something went wrong.');
});

XHR.open('POST', 'https://www.googleapis.com/oauth2/v3/token');
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XHR.send(urlEncodedData)

之后我有我的访问令牌,我可以关注有关使用嵌入API的这些教程,但授权如此:

After that I have my access token and I can follow these tutorials on using the embed API, but authorizing like so:

gapi.analytics.auth.authorize({
    serverAuth: {
        access_token: token
    }
});

不要忘记您必须授予服务帐户查看内容的权限,就像任何内容一样其他用户。当然,如果服务帐户被授权执行除只读之外的任何操作,那将是一个非常糟糕的主意。

Don't forget that you have to give the service account permission to view the content, just like any other user. And of course, it would be a really bad idea if the service account was authorized to do anything other than read only.

可能还有关于计时和问题的问题令牌到期,我会遇到,但到目前为止一直很好。

There are probably also issues with regards to timing and token expiring that I will run into, but so far so good.

这篇关于如何获取Google服务帐户访问令牌javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆