Skip to content

Commit 3c5fd66

Browse files
authored
fix: prepare for request type event and simple response (#3)
2 parents d0f6ac1 + 849b4b0 commit 3c5fd66

File tree

3 files changed

+35
-19
lines changed

3 files changed

+35
-19
lines changed

index.js

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,42 @@
1-
const jwt = require("jsonwebtoken");
1+
const jwt = require('jsonwebtoken');
22

33
// JWT constants.
4-
const JWT_PUBLIC_KEY = process.env.JWT_PUBLIC_KEY;
5-
const JWT_RS256_ALGORITHM = "RS256";
6-
7-
// General constants.
8-
const STRING_TYPE = "string";
4+
const JWT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----\n${process.env.JWT_PUBLIC_KEY}\n-----END PUBLIC KEY-----`;
95

6+
/**
7+
* @param {AWSLambda.APIGatewayRequestAuthorizerEventV2} event
8+
* @returns {Promise<boolean>}
9+
*/
1010
exports.handler = async (event) => {
11-
// Gets event header.
12-
const header =
13-
typeof event.header === STRING_TYPE
14-
? JSON.parse(event.header)
15-
: event.header;
11+
const token = event.identitySource?.[0]?.split('Bearer ')?.[1];
1612

17-
// Needs to be authorized by a given token.
18-
const token = header.token;
13+
if (!token) {
14+
console.log('Missing token');
15+
return { isAuthorized: false };
16+
}
1917

20-
// Object that stores values used by 'jsonwebtoken - verify' function call.
2118
const jwtSettings = {
2219
publicKey: JWT_PUBLIC_KEY,
2320
options: {
24-
algorithms: [JWT_RS256_ALGORITHM],
21+
algorithms: ['RS256'],
2522
},
2623
};
2724

2825
try {
29-
// Verify and decode the JWT token.
3026
const decoded = jwt.verify(
3127
token,
3228
jwtSettings.publicKey,
3329
jwtSettings.options
3430
);
3531

3632
if (decoded.sub == null) {
37-
return false;
33+
console.log('Missing sub claim');
34+
return { isAuthorized: false };
3835
}
3936

40-
return true;
37+
return { isAuthorized: true };
4138
} catch (error) {
42-
return false;
39+
console.log('Token validation failed', token);
40+
return { isAuthorized: false };
4341
}
4442
};

package-lock.json

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
{
22
"dependencies": {
33
"jsonwebtoken": "^9.0.2"
4+
},
5+
"devDependencies": {
6+
"@types/aws-lambda": "^8.10.125"
47
}
58
}

0 commit comments

Comments
 (0)