This repository has been archived by the owner on Jul 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
68 lines (57 loc) · 2.26 KB
/
index.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
const jwt = require('jsonwebtoken');
console.log('Loading jwtAuthorizer');
exports.handler = function(event, context, callback) {
console.log('Received event', JSON.stringify(event, null, 2));
// remove the 'Bearer ' prefix from the auth token
const token = event.authorizationToken.replace(/Bearer /g, '');
// parse all API options from the event, in case we need some of them
const apiOptions = getApiOptions(event);
console.log('API Options', JSON.stringify(apiOptions, null, 2));
// config data to check the content of the token and public key to verify the signature of the token
const config = {
audience: process.env.TOKEN_AUDIENCE,
issuer: process.env.TOKEN_ISSUER,
};
const secret = process.env.TOKEN_SECRET;
// verify the token with publicKey and config and return proper AWS policy document
jwt.verify(token, secret, config, (err, verified) => {
if (err) {
console.error('JWT Error', err, err.stack);
callback(null, denyPolicy('anonymous', event.methodArn));
} else {
callback(null, allowPolicy(verified.sub, event.methodArn));
}
});
};
const getApiOptions = function(event) {
const apiOptions = {};
const tmp = event.methodArn.split(':');
const apiGatewayArnTmp = tmp[5].split('/');
apiOptions.awsAccountId = tmp[4];
apiOptions.region = tmp[3];
apiOptions.restApiId = apiGatewayArnTmp[0];
apiOptions.stageName = apiGatewayArnTmp[1];
return apiOptions;
};
const denyPolicy = function(principalId, resource) {
return generatePolicy(principalId, 'Deny', resource);
};
const allowPolicy = function(principalId, resource) {
return generatePolicy(principalId, 'Allow', resource);
};
const generatePolicy = function(principalId, effect, resource) {
const authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
const policyDocument = {};
policyDocument.Version = '2012-10-17'; // default version
policyDocument.Statement = [];
const statementOne = {};
statementOne.Action = 'execute-api:Invoke'; // default action
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
return authResponse;
};