Skip to content

Instantly share code, notes, and snippets.

@joshtwist
Last active February 3, 2016 20:37
Show Gist options
  • Save joshtwist/4402781 to your computer and use it in GitHub Desktop.
Save joshtwist/4402781 to your computer and use it in GitHub Desktop.
Function that creates a ZUMO JWT token. Specify the date, the aud, the userId and your Mobile Services master key, e.g. var expiry = new Date().setUTCDate(new Date().getUTCDate() + 1); // expires in one day from nowvar jwt = zumoJwt(expiry, "your-aud", "unique string for this user", "yourmasterkey");
function zumoJwt(expiryDate, aud, userId, masterKey) {
var crypto = require('crypto');
function base64(input) {
return new Buffer(input, 'utf8').toString('base64');
}
function urlFriendly(b64)
{
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
}
function signature(input) {
var key = crypto.createHash('sha256').update(masterKey + "JWTSig").digest('binary');
var str = crypto.createHmac('sha256', key).update(input).digest('base64');
return urlFriendly(str);
}
var s1 = '{"alg":"HS256","typ":"JWT","kid":0}';
var j2 = {
"exp":expiryDate.valueOf() / 1000,
"iss":"urn:microsoft:windows-azure:zumo",
"ver":2,
"aud":aud,
"uid":userId
};
var s2 = JSON.stringify(j2);
var b1 = urlFriendly(base64(s1));
var b2 = urlFriendly(base64(s2));
var b3 = signature(b1 + "." + b2);
return [b1,b2,b3].join(".");
}
@PatHat
Copy link

PatHat commented Feb 3, 2016

Hello. I looking to write a JavaScript code that can do Server to Server OAuth2 (i.e., no user interaction or consent). I have the necessary credentials (ID and private key) set up in my Google domain for a Service account. All I need now is the JavaScript to make it happen. I checked out the Google JS library but it does not seem to support this particular OAuth flow (i.e., Server to Server, also called 2-legged OAuth I believe). Thoughts on this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment