Repository navigation
Expand file tree
/
Copy pathvalidate-jwt.ts
More file actions
60 lines (51 loc) · 1.75 KB
/
Copy pathvalidate-jwt.ts
File metadata and controls
60 lines (51 loc) · 1.75 KB
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
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { decode, verify } from "jsonwebtoken";
import jwksClient, { SigningKey, RsaSigningKey } from "jwks-rsa";
// jwks client is cached at this scope so it can be reused across Lambda invocations
let jwksRsa: jwksClient.JwksClient;
function isRsaSigningKey(key: SigningKey): key is RsaSigningKey {
return !!(key as any).rsaPublicKey;
}
async function getSigningKey(jwksUri: string, kid: string) {
// Retrieves the public key that corresponds to the private key with which the token was signed
if (!jwksRsa) {
jwksRsa = jwksClient({ cache: true, rateLimit: true, jwksUri });
}
return new Promise<string>((resolve, reject) =>
jwksRsa.getSigningKey(kid, (err, jwk) =>
err
? reject(err)
: resolve(isRsaSigningKey(jwk) ? jwk.rsaPublicKey : jwk.publicKey)
)
);
}
export async function validate(
jwtToken: string,
jwksUri: string,
issuer: string,
audience: string
) {
const decodedToken = decode(jwtToken, { complete: true }) as {
[key: string]: any;
};
if (!decodedToken) {
throw new Error("Cannot parse JWT token");
}
// The JWT contains a "kid" claim, key id, that tells which key was used to sign the token
const kid = decodedToken["header"]["kid"];
const jwk = await getSigningKey(jwksUri, kid);
// Verify the JWT
// This either rejects (JWT not valid), or resolves (JWT valid)
const verificationOptions = {
audience,
issuer,
ignoreExpiration: false,
};
// JWT's from Cognito are JSON objects
return new Promise<{ [key: string]: any }>((resolve, reject) =>
verify(jwtToken, jwk, verificationOptions, (err, decoded) =>
err ? reject(err) : resolve(decoded!)
)
);
}