Posted on 2 mins read

I have been experimenting with integrating the Amazon API Gateway and Red Hat’s Keycloak (more on these experiments to come). The API Gateway has a few ways to authenticate & authorize with the obvious one being to use Amazon Cognito. However since Feb 2016 you have been able to use Amazon Lambda functions as Custom Authorizers. When configured in API Gateway along with a HTTP header such as Authorization, your Lambda function will be called with something like the following:

{
    "type":"TOKEN",
    "authorizationToken":"<Incoming bearer token>",
    "methodArn":"arn:aws:execute-api:<Region id>:<Account id>:<API id>/<Stage>/<Method>/<Resource path>"
}

Which your Lambda should respond with either Unauthorized to return a 401 UNAUTHORIZED response or a reasonably complex json policy document to either allow access or generate a 403 FORBIDDEN:

{
  "principalId": "xxxxxxx", // the principal user identification associated with the token send by the client
  "policyDocument": { // example policy shown below, but this value is any valid policy
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "execute-api:Invoke"
        ],
        "Resource": [
          "arn:aws:execute-api:us-east-1:xxxxxxxxxxxx:xxxxxxxx:/test/*/mydemoresource/*"
        ]
      }
    ]
  }
}

Fortunately Amazon have provided us with some Lambda blueprints for Java, Javascript and Python. I went for the Python blueprint but loading the code into Sublime made the linter very mad. It seems like the Python code was written by someone who wasn’t overly familiar with idiomatic Python. So of course I groomed it and have shared in a gist for others to use.

I’ve avoided changing the HttpVerb class into a Python 3 enum for those of you on Python 2.7 and have been pragmatic about a couple of line lengths where it suited readability.