Skip to content

Instantly share code, notes, and snippets.

@zbryikt
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zbryikt/dbd76f0d78d97245740b to your computer and use it in GitHub Desktop.
Save zbryikt/dbd76f0d78d97245740b to your computer and use it in GitHub Desktop.
retrieve access token using google service account

Here is a code snippet to retrieve access token via google service account.

require! <[crypto urlsafe-base64 request]>
#service account authentication
#https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests
header = {"alg":"RS256","typ":"JWT"}
accinfo = do
iss: "service account email"
pk: "service account private key"
id: "dataset id"
claim-set = {
"iss": accinfo.iss
"scope":"https://www.googleapis.com/auth/datastore https://www.googleapis.com/auth/userinfo.email",
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp": parseInt(new Date!getTime! / 1000) + 3600
"iat": parseInt(new Date!getTime! / 1000)
}
header64 = urlsafe-base64.encode(Buffer(JSON.stringify(header)))
claim64 = urlsafe-base64.encode(Buffer(JSON.stringify(claim-set)))
console.log header64
console.log claim64
content = "#{header64}.#{claim64}"
signer = crypto.createSign \RSA-SHA256
signer.update content
sign = signer.sign accinfo.pk
sign64 = urlsafe-base64.encode(sign)
console.log sign64
(e,r,b) <- request {
url: \https://www.googleapis.com/oauth2/v3/token
method: \POST
headers: do
"Content-Type": \application/x-www-form-urlencoded
form: do
grant_type: \urn:ietf:params:oauth:grant-type:jwt-bearer
assertion: "#{content}.#{sign64}"
}, _
if e => console.log e.toString!
b = JSON.parse(b)
access_token = b.access_token
token_type = b.token_type
console.log "#{token_type} #{access_token}"
t1 = new Date!getTime!
(e,r,b) <- request {
url: "https://www.googleapis.com/datastore/v1beta2/datasets/#{accinfo.id}/runQuery"
method: \POST
headers: do
"Authorization": "#{token_type} #{access_token}"
"Content-Type": \application/json
body: JSON.stringify({query: kinds: [{name: \test}]})
}, _
if e => console.log e.toString!
console.log b
t2 = new Date!getTime!
console.log t2 - t1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment