Skip to content

Instantly share code, notes, and snippets.

@JamesMarino
Created October 29, 2017 00:12
Show Gist options
  • Save JamesMarino/97926660eb6ab15ede8aa1bdfe1e0592 to your computer and use it in GitHub Desktop.
Save JamesMarino/97926660eb6ab15ede8aa1bdfe1e0592 to your computer and use it in GitHub Desktop.
Lambda Custom Authoriser API Gateway
exports.handler = (event, context, callback) => {
var token = event.authorizationToken;
switch (token.toLowerCase()) {
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.methodArn));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
}
};
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context = {
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
};
return authResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment