Skip to content

Instantly share code, notes, and snippets.

@cjdenio
Created January 22, 2020 18:17
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 cjdenio/ffa84a33bcdbfd798f5a59762d7450e5 to your computer and use it in GitHub Desktop.
Save cjdenio/ffa84a33bcdbfd798f5a59762d7450e5 to your computer and use it in GitHub Desktop.
Node.js - generate JSON Web Token for Google Cloud APIs

In order to authorize a Google Cloud Platform API with a service account, you'll need an OAuth token. Service accounts don't follow the regular OAuth flow, though. To use this script, you'll need request. Run npm install request to install it. Learn more about Google's OAuth flow for service accounts here.

// Path to downloaded .json file for service account
const GOOGLE_APPLICATION_CREDENTIALS = ""
// Scopes to add to the token
const SCOPES = []
const crypto = require('crypto')
const fs = require('fs')
const request = require('request')
const credentials = JSON.parse(fs.readFileSync(GOOGLE_APPLICATION_CREDENTIALS))
var header = Buffer.from(JSON.stringify({
alg: "RS256",
typ: "JWT"
})).toString("base64")
var payload = Buffer.from(JSON.stringify({
iss: credentials.client_email,
scope: SCOPES.join(" "),
aud: credentials.token_uri,
iat: Math.round(new Date().getTime() / 1000),
exp: Math.round(new Date().getTime() / 1000) + (30 * 60)
})).toString("base64")
var sign = crypto.createSign("RSA-SHA256")
sign.write(header + "." + payload)
sign.end()
var signature = sign.sign(credentials.private_key, "base64")
var jwt = header + "." + payload + "." + signature
// Now, let's get the token from Google
request("https://oauth2.googleapis.com/token", {
method: "POST",
form: {
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: jwt
}
}, (err, resp, body) => {
body = JSON.parse(body)
console.log("Access token: " + body.access_token)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment