Skip to content

Instantly share code, notes, and snippets.

@zmej-serow
Last active August 9, 2019 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmej-serow/4e3392b76bd343d49417b59662a43224 to your computer and use it in GitHub Desktop.
Save zmej-serow/4e3392b76bd343d49417b59662a43224 to your computer and use it in GitHub Desktop.
Request-based AWS Lambda authorizer
def lambda_handler(event, context):
principalId = 'me'
tmp = event['methodArn'].split(':')
apiGatewayArnTmp = tmp[5].split('/')
awsAccountId = tmp[4]
headers = event['headers']
queryStringParameters = event['queryStringParameters']
pathParameters = event['pathParameters']
stageVariables = event['stageVariables']
region = tmp[3];
restApiId = apiGatewayArnTmp[0]
stage = apiGatewayArnTmp[1]
method = apiGatewayArnTmp[2]
resource = '/' # root resource
if apiGatewayArnTmp[3]:
resource += apiGatewayArnTmp[3]
authResponse = {}
if (headers['HeaderAuth1'] == "1" and queryStringParameters['QueryString1'] == "2" and stageVariables['StageVar1'] == "3"):
return generateAllow(principalId, event['methodArn'])
else:
raise Exception("Unauthorized")
def generatePolicy(principalId, effect, resource):
authResponse = {}
authResponse['principalId'] = principalId
if (effect and resource):
policyDocument = {}
policyDocument['Version'] = '2012-10-17'
policyDocument['Statement'] = []
statementOne = {}
statementOne['Action'] = 'execute-api:Invoke';
statementOne['Effect'] = effect
statementOne['Resource'] = resource
policyDocument['Statement'].append(statementOne)
authResponse['policyDocument'] = policyDocument
context = {
'key': 'value', # $context.authorizer.key -> value
'number': 1,
'bool': True
}
authResponse['context'] = context
return authResponse
def generateAllow(principalId, resource):
return generatePolicy(principalId, 'Allow', resource)
def generateDeny(principalId, resource):
return generatePolicy(principalId, 'Deny', resource)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment