-
Notifications
You must be signed in to change notification settings - Fork 7
/
JWT.gs
62 lines (51 loc) · 1.37 KB
/
JWT.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @namespace JWT
* a namespace to generate a firebase jwt
*/
var JWT = (function (ns) {
/**
* generate a jwt for firebase using default settings
* @param {object} data the data pockage
* @param {string} secret the jwt secret
*/
ns.generateJWT = function(data, secret) {
var header = getHeader_ ();
var claims = getClaims_ (data);
var jwt = header + "." + claims;
// now sign it
var signature = Utilities.computeHmacSha256Signature (jwt, secret);
var signed = unPad_ (Utilities.base64EncodeWebSafe(signature));
// and thats the jwt
return jwt + "." + signed;
};
/**
* generate a jwt header
* return {string} a jwt header b64
*/
function getHeader_ () {
return unPad_(Utilities.base64EncodeWebSafe(JSON.stringify( {
"alg": "HS256",
"typ": "JWT"
})));
}
/**
* generate a jwt claim for firebase
* return {string} a jwt claimsm payload b64
*/
function getClaims_ (data) {
return unPad_ (Utilities.base64EncodeWebSafe( JSON.stringify( {
"d" : data || {},
"iat": Math.floor(new Date().getTime()/1000),
"v": 0
})));
}
/**
* remove padding from base 64
* @param {string} b64 the encoded string
* @return {string} padding removed
*/
function unPad_ (b64) {
return b64 ? b64.split ("=")[0] : b64;
}
return ns;
})(JWT || {});