forked from queueit/KnownUser.V3.Cloudflare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validateToken.ts
48 lines (41 loc) · 1.14 KB
/
validateToken.ts
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
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
const verifyToken = async (token: any, pem: any): Promise<boolean> => {
return new Promise((resolve) => {
jwt.verify(token, pem, function(err: any, payload: any) {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
}
export const validateToken = async (token: any): Promise<boolean> => {
const jwk = await CognitoJWK.get(USER_POOL_ID, { type: "json" });
const { keys } = jwk;
let pems = {};
for (let i = 0; i < keys.length; i++) {
// Convert each key to PEM
let key_id = keys[i].kid;
let modulus = keys[i].n;
let exponent = keys[i].e;
let key_type = keys[i].kty;
let jwk = { kty: key_type, n: modulus, e: exponent};
let pem = jwkToPem(jwk);
pems[key_id] = pem;
}
// validate the token
let decodedJwt = jwt.decode(token, {complete: true});
if (!decodedJwt) {
console.log("Not a valid JWT token");
return false;
}
let kid = decodedJwt.header.kid;
let pem = pems[kid];
if (!pem) {
console.log('Invalid pem');
return false;
}
return await verifyToken(token, pem);
}