Skip to content

Instantly share code, notes, and snippets.

@onlinemad
Created December 11, 2014 06:54
Show Gist options
  • Save onlinemad/28341a343ecde186a410 to your computer and use it in GitHub Desktop.
Save onlinemad/28341a343ecde186a410 to your computer and use it in GitHub Desktop.
Get Google JWT token.
var fs = require('fs');
var jwt = require('jsonwebtoken');
var request = require('request');
// constants
var GOOGLE_OAUTH2_URL = 'https://accounts.google.com/o/oauth2/token';
var iat = Math.floor(Date.now() / 1000);
var exp = iat + 60 * 60;
var payload = {
iss: '123520686343-k6tfn73sentmh0ss5nu67kniorbcta8n@developer.gserviceaccount.com',
scope: 'https://www.googleapis.com/auth/devstorage.full_control',
aud: GOOGLE_OAUTH2_URL,
exp: exp,
iat: iat
};
console.log('request payload', payload);
// sign with RSA SHA256
var cert = fs.readFileSync('google_cloud_key.pem'); // get private key
var token = jwt.sign(payload, cert, { algorithm: 'RS256' });
request.post(GOOGLE_OAUTH2_URL, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
form: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token
}
}, function(err, res, body) {
if (err) {
console.log(err);
} else {
console.log('response from OAuth server');
console.log('http status', res.statusCode);
console.log('body', body);
}
if (res.statusCode != 200) {
err = new Error(
'failed to obtain an authentication token, request failed with HTTP code ' +
res.statusCode + ': ' + body.error
);
err.statusCode = res.statusCode;
err.body = body;
console.log(err);
} else {
try {
body = JSON.parse(body);
} catch (e) {
console.log(new Error('failed to parse response body: ' + body));
}
console.log(body);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment