-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.ts
63 lines (56 loc) · 1.5 KB
/
index.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { APIGatewayRequestAuthorizerHandler } from "aws-lambda";
import { CognitoJwtVerifier } from "aws-jwt-verify";
const UserPoolId = process.env.USER_POOL_ID!;
const AppClientId = process.env.APP_CLIENT_ID!;
export const handler: APIGatewayRequestAuthorizerHandler = async (event, context) => {
try {
const verifier = CognitoJwtVerifier.create({
userPoolId: UserPoolId,
tokenUse: "id",
clientId: AppClientId,
});
const encodedToken = event.queryStringParameters!.idToken!;
const payload = await verifier.verify(encodedToken);
console.log("Token is valid. Payload:", payload);
return allowPolicy(event.methodArn, payload);
} catch (error: any) {
console.log(error.message);
return denyAllPolicy();
}
};
const denyAllPolicy = () => {
return {
principalId: "*",
policyDocument: {
Version: "2012-10-17",
Statement: [
{
Action: "*",
Effect: "Deny",
Resource: "*",
} as const,
],
},
};
};
const allowPolicy = (methodArn: string, idToken: any) => {
return {
principalId: idToken.sub,
policyDocument: {
Version: "2012-10-17",
Statement: [
{
Action: "execute-api:Invoke",
Effect: "Allow",
Resource: methodArn,
} as const,
],
},
context: {
// set userId in the context
userId: idToken.sub,
},
};
};