Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

How to obtain Google service account access token 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.

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'
}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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);

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 = "<[email protected]";
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-----
MIIC....
-----END PRIVATE KEY-----
";`enter code here`

Then generated a signed JWT with

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

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...