Lambda Authorizer

The Alexa Event Handler Lambda function will receive the JSON payload from the Alexa Skill and send it to API Gateway for authentication and routing to the relevant Lambda function. First, API Gateway authorizes the request using a Lambda authorizer.

This function will verify the access token from the request and optionally check it against an internal DynamoDB database. For example, the authorizer might look up the hotel customer’s credentials to determine whether the user is authorized to receive the requested content.

After the request has been authorized API Gateway sends the request on to the specified API URI which invokes the Lambda function associated with that specified logic. For this example, we will send the request on to the Lambda function which triggers IoT Core functionality.

import json

#Format return policy that API Gateway expects
def generatePolicy(principalId, effect, resource):
  return {
    'principalId': principalId,
    'policyDocument': {
      'Version': '2012-10-17',
      'Statement': [{
        'Action': 'execute-api:Invoke',
        'Effect': effect,
        'Resource': resource
      }]
    }
  };
def customLogicFunction(token):
    #Run your custom authorization here
    #i.e. Check your DynamoDB table for token associated with user
    #Return true or false

def lambda_handler(event, context):
    
    #if(customLogicFunction(event['authorizationToken']) == true)
        return generatePolicy('user', 'Allow', event['methodArn'])
    
    #else
      #return generatePolicy('user', 'Deny', event['methodArn'])

This is the Lambda authorizer that does your custom authorization logic. Notice the format of response API Gateway is expecting. API Gateway passes the source token to this Lambda authorizer function in the event.authorizationToken attribute. The Lambda authorizer function reads the token and acts as follows: If the token value is ‘Allow’, the authorizer function returns a 200 OK HTTP response and an IAM policy that looks like the following, and the method request succeeds:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Allow",
      "Resource": "arn:aws:execute-api:us-east-1:xxxxxxxxxxxx:m88ssxznb7/ESTestInvoke-stage/GET/"
    }
  ]
}

Finally be sure to set the Lambda function trigger to API Gateway, associate a role based on least privilege, and set the timeout time to 10 seconds.