-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.js
92 lines (74 loc) · 2.25 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
require("dotenv").config();
const https = require("https");
function toBase64URL(json) {
const jsonString = JSON.stringify(json);
const btyeArray = Buffer.from(jsonString);
return btyeArray
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
}
function getOAuthToken(jwt) {
return new Promise((resolve, reject) => {
var option = {
hostname: "oauth2.googleapis.com",
path: `/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${jwt}`,
method: "POST",
port: 443,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
var req = https.request(option, function (res) {
var result = "";
res.on("data", function (chunk) {
result += chunk;
});
res.on("end", function () {
resolve(result);
});
});
req.on("error", function (err) {
reject(err);
});
req.end();
});
}
async function jwtToBearer() {
const header = {
alg: "RS256",
typ: "JWT",
};
const now = new Date().getTime() / 1000;
const oneHour = 60 * 60;
const expireTime = now + oneHour;
const claimSet = {
iss: process.env.SERVICE_ACCOUNT_EMAIL,
iat: now,
exp: expireTime,
scope: process.env.CLAIM_SET_SCOPE,
aud: "https://oauth2.googleapis.com/token",
};
const encodedHeader = toBase64URL(header);
const encodedClaimSet = toBase64URL(claimSet);
const crypto = require("crypto");
const signer = crypto.createSign("RSA-SHA256");
signer.write(encodedHeader + "." + encodedClaimSet);
signer.end;
const signature = signer.sign(process.env.PRIVATE_KEY, "base64");
const encodedSignature = signature
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
const jwt = `${encodedHeader}.${encodedClaimSet}.${encodedSignature}`;
const result = await getOAuthToken(jwt).catch((err) => {
console.debug(err);
});
const json = JSON.parse(result);
return json;
}
jwtToBearer();
module.exports = {
jwtToBearer,
};