-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathjwt.js
46 lines (40 loc) · 1.55 KB
/
jwt.js
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
import crypto from "k6/crypto";
import encoding from "k6/encoding";
import {sleep} from "k6";
const algToHash = {
HS256: "sha256",
HS384: "sha384",
HS512: "sha512"
};
function sign(data, hashAlg, secret) {
let hasher = crypto.createHMAC(hashAlg, secret);
hasher.update(data);
// Some manual base64 rawurl encoding as `Hasher.digest(encodingType)`
// doesn't support that encoding type yet.
return hasher.digest("base64").replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
}
function encode(payload, secret, algorithm) {
algorithm = algorithm || "HS256";
let header = encoding.b64encode(JSON.stringify({ typ: "JWT", alg: algorithm }), "rawurl");
payload = encoding.b64encode(JSON.stringify(payload), "rawurl", "s");
let sig = sign(header + "." + payload, algToHash[algorithm], secret);
return [header, payload, sig].join(".");
}
function decode(token, secret, algorithm) {
let parts = token.split('.');
let header = JSON.parse(encoding.b64decode(parts[0], "rawurl", "s"));
let payload = JSON.parse(encoding.b64decode(parts[1], "rawurl", "s"));
algorithm = algorithm || algToHash[header.alg];
if (sign(parts[0] + "." + parts[1], algorithm, secret) != parts[2]) {
throw Error("JWT signature verification failed");
}
return payload;
}
export default function() {
let message = { key2: "value2" };
let token = encode(message, "secret");
console.log("encoded", token);
let payload = decode(token, "secret");
console.log("decoded", JSON.stringify(payload));
sleep(1)
}