|
1 |
| -const jwt = require("jsonwebtoken"); |
| 1 | +const jwt = require('jsonwebtoken'); |
2 | 2 |
|
3 | 3 | // 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-----`; |
9 | 5 |
|
| 6 | +/** |
| 7 | + * @param {AWSLambda.APIGatewayRequestAuthorizerEventV2} event |
| 8 | + * @returns {Promise<boolean>} |
| 9 | + */ |
10 | 10 | 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]; |
16 | 12 |
|
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 | + } |
19 | 17 |
|
20 |
| - // Object that stores values used by 'jsonwebtoken - verify' function call. |
21 | 18 | const jwtSettings = {
|
22 | 19 | publicKey: JWT_PUBLIC_KEY,
|
23 | 20 | options: {
|
24 |
| - algorithms: [JWT_RS256_ALGORITHM], |
| 21 | + algorithms: ['RS256'], |
25 | 22 | },
|
26 | 23 | };
|
27 | 24 |
|
28 | 25 | try {
|
29 |
| - // Verify and decode the JWT token. |
30 | 26 | const decoded = jwt.verify(
|
31 | 27 | token,
|
32 | 28 | jwtSettings.publicKey,
|
33 | 29 | jwtSettings.options
|
34 | 30 | );
|
35 | 31 |
|
36 | 32 | if (decoded.sub == null) {
|
37 |
| - return false; |
| 33 | + console.log('Missing sub claim'); |
| 34 | + return { isAuthorized: false }; |
38 | 35 | }
|
39 | 36 |
|
40 |
| - return true; |
| 37 | + return { isAuthorized: true }; |
41 | 38 | } catch (error) {
|
42 |
| - return false; |
| 39 | + console.log('Token validation failed', token); |
| 40 | + return { isAuthorized: false }; |
43 | 41 | }
|
44 | 42 | };
|
0 commit comments