/
verifyToken.js
69 lines (56 loc) · 1.63 KB
/
verifyToken.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
import jwt from 'jsonwebtoken'
import jwkToPem from 'jwk-to-pem'
import dotenv from 'dotenv'
import debug from 'debug'
import jwkSet from './JwkSet.json'
dotenv.config()
const log = debug('graphql:verifyToken')
const userPoolId = 'https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_kYvMedesC'
const pems = jwkSet.keys.reduce((tmpPems, key) => {
const pem = jwkToPem({
kty: key.kty,
n: key.n,
e: key.e,
})
return { ...tmpPems, [key.kid]: pem }
}, {})
function verifyToken(jwtToken, shouldBeAccessToken) {
return new Promise((resolve, reject) => {
const decodedJWT = jwt.decode(jwtToken, { complete: true })
if (!decodedJWT) {
log('Not a valid JWT token')
reject('Not a valid JWT token')
}
if (decodedJWT.payload.iss !== userPoolId) {
log('invalid issuer')
reject({
message: 'invalid issuer',
iss: decodedJWT.payload,
})
}
if (shouldBeAccessToken && decodedJWT.payload.token_use !== 'access') {
log('Not an access token')
reject('Not an access token')
}
const kid = decodedJWT.header.kid
const pem = pems[kid]
if (!pem) {
log('Invalid access token')
reject('Invalid access token')
}
jwt.verify(jwtToken, pem, { issuer: userPoolId }, (error, payload) => {
if (error) {
log('Unauthorized signature for this JWT Token')
reject('Unauthorized signature for this JWT Token')
} else {
resolve(payload)
}
})
})
}
export function verifyAccessToken(token) {
return verifyToken(token, true)
}
export function verifyIdToken(token) {
return verifyToken(token, false)
}