Skip to content

senzing-garage/aws-lambda-cognito-authorizer

Repository files navigation

aws-lambda-cognito-authorizer

If you are beginning your journey with Senzing, please start with Senzing Quick Start guides.

You are in the Senzing Garage where projects are "tinkered" on. Although this GitHub repository may help you understand an approach to using Senzing, it's not considered to be "production ready" and is not considered to be part of the Senzing product. Heck, it may not even be appropriate for your application of Senzing!

Synopsis

An AWS Lambda Python program for checking a token for authentication.

Overview

The instructions show how to generate a package that is loaded onto AWS S3 and used by https://github.com/senzing-garage/aws-cloudformation-ecs-poc-simple AWS Cloudformation.

Contents

  1. Preamble
    1. Legend
  2. Related artifacts
  3. Architecture
    1. How to add Cognito Authorizer to a Websocket API gateway
  4. Demonstrate using Command Line Interface
    1. Prerequisites for CLI
    2. Download
    3. Run command
  5. Demonstrate using Docker
    1. Prerequisites for Docker
    2. Run Docker container
  6. Develop
    1. Prerequisites for development
    2. Clone repository
    3. Build Docker image
    4. Test Docker image
    5. Make package for S3
  7. Advanced
  8. Errors
  9. References

Preamble

At Senzing, we strive to create GitHub documentation in a "don't make me think" style. For the most part, instructions are copy and paste. Whenever thinking is needed, it's marked with a "thinking" icon πŸ€”. Whenever customization is needed, it's marked with a "pencil" icon ✏️. If the instructions are not clear, please let us know by opening a new Documentation issue describing where we can improve. Now on with the show...

Legend

  1. πŸ€” - A "thinker" icon means that a little extra thinking may be required. Perhaps there are some choices to be made. Perhaps it's an optional step.
  2. ✏️ - A "pencil" icon means that the instructions may need modification before performing.
  3. ⚠️ - A "warning" icon means that something tricky is happening, so pay attention.

Related artifacts

  1. https://github.com/senzing-garage/aws-cloudformation-ecs-poc-simple AWS Cloudformation

Architecture

The following is an architecture showcasing how the websocket API gateway interacts with the aws lambda cognito authorizer.

Architecture diagram

How to add Cognito Authorizer to a Websocket API gateway

  1. Visit the AWS Console for API Gateway.
  2. On the left hand navigation bar, choose the APIs tab.
  3. Click on a Websocket API Gateway that you want to attach a Cognito Authorizer.
  4. On the bottom left hand navigation bar, choose the Authorizers tab.
  5. Click on the "Create New Authorizer" button.
  6. In the "Create Authorizer" pane:
    1. Set the Authorizer name.
    2. Set the Lambda Function to the Cognito Authorizer.
    3. Set Identity Sources to the request parameters used for authorization. In the example below, we used the request parameter token.
  7. Once done, click on the "create" button.

Create Authorizer

  1. On the bottom left hand navigation bar, choose the Routes tab.
  2. In the Routes pane, choose the $connect route.
  3. In the $connect pane, click on Route Request.
  4. Change the authorization to the cognito authorizer lambda function.

Set route request setting

  1. Click on Route Overview and if it looks like the example below, you have successfully added the cognito authorizer to your Websocket API gateway.

Add authorizer to route request

Demonstrate using Command Line Interface

Prerequisites for CLI

πŸ€” The following tasks need to be complete before proceeding. These are "one-time tasks" which may already have been completed.

  1. Install Python dependencies:
    1. See requirements.txt for list
      1. Installation hints

Download

  1. Get a local copy of cognito_authorizer.py. Example:

    1. ✏️ Specify where to download file. Example:

      export SENZING_DOWNLOAD_FILE=~/cognito_authorizer.py
    2. Download file. Example:

      curl -X GET \
        --output ${SENZING_DOWNLOAD_FILE} \
        https://raw.githubusercontent.com/Senzing/aws-lambda-cognito-authorizer/main/cognito_authorizer.py
    3. Make file executable. Example:

      chmod +x ${SENZING_DOWNLOAD_FILE}
  2. πŸ€” Alternative: The entire git repository can be downloaded by following instructions at Clone repository

Run command

  1. Run the command. Example:

    ${SENZING_DOWNLOAD_FILE}

Demonstrate using Docker

Prerequisites for Docker

πŸ€” The following tasks need to be complete before proceeding. These are "one-time tasks" which may already have been completed.

  1. The following software programs need to be installed:
    1. docker

Run Docker container

  1. Run Docker container. Example:

    docker run \
      --interactive \
      --rm \
      --tty \
      senzing/cognito-authorizer

    Note: Because this is built to run in an AWS Lambda environment, errors will be seen when running outside of that environment.

Develop

The following instructions are used when modifying and building the Docker image.

Prerequisites for development

πŸ€” The following tasks need to be complete before proceeding. These are "one-time tasks" which may already have been completed.

  1. The following software programs need to be installed:
    1. git
    2. make
    3. docker

Clone repository

For more information on environment variables, see Environment Variables.

  1. Set these environment variable values:

    export GIT_ACCOUNT=senzing
    export GIT_REPOSITORY=aws-lambda-cognito-authorizer
    export GIT_ACCOUNT_DIR=~/${GIT_ACCOUNT}.git
    export GIT_REPOSITORY_DIR="${GIT_ACCOUNT_DIR}/${GIT_REPOSITORY}"
  2. Using the environment variables values just set, follow steps in clone-repository to install the Git repository.

Build Docker image

Since the Docker image is based on public.ecr.aws/lambda/python:3.8, logging into AWS Elastic Container Registry (ECR) is required.

  1. Set AWS environment variables. Example:

    export AWS_ACCESS_KEY_ID=$(jq --raw-output ".Credentials.AccessKeyId" ~/aws-sts-get-session-token.json)
    export AWS_SECRET_ACCESS_KEY=$(jq --raw-output ".Credentials.SecretAccessKey" ~/aws-sts-get-session-token.json)
    export AWS_SESSION_TOKEN=$(jq --raw-output ".Credentials.SessionToken" ~/aws-sts-get-session-token.json)
    export AWS_DEFAULT_REGION=$(aws configure get default.region)
  2. Login Example:

    aws ecr-public get-login-password \
      --region us-east-1 \
    | docker login \
      --username AWS \
      --password-stdin public.ecr.aws/senzing
  3. Option #1: Using docker command and GitHub.

    sudo docker build \
      --tag senzing/template \
      https://github.com/senzing-garage/aws-lambda-cognito-authorizer.git#main
  4. Option #2: Using docker command and local repository.

    cd ${GIT_REPOSITORY_DIR}
    sudo docker build --tag senzing/cognito-authorizer .
  5. Option #3: Using make command.

    cd ${GIT_REPOSITORY_DIR}
    sudo make docker-build

    Note: sudo make docker-build-development-cache can be used to create cached Docker layers.

Test Docker image

  1. Download the AWS Lambda Runtime Interface Emulator and make executable. Example:

    mkdir -p ~/aws-lambda-rie
    curl -Lo ~/aws-lambda-rie/aws-lambda-rie https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie
    chmod +x ~/aws-lambda-rie/aws-lambda-rie
  2. Set the required environment variables

    export USERPOOL_ID=<insert user pool id>
    export APP_CLIENT_ID=<insert app client id>
    export AWS_REGION=<insert aws region e.g. us-east-1>
  3. Run docker container to start a service. Example:

    docker run \
      --entrypoint /aws-lambda/aws-lambda-rie \
      --interactive \
      --publish 9001:8080 \
      --rm \
      --tty \
      --env USERPOOL_ID=${USERPOOL_ID} \
      --env APP_CLIENT_ID=${APP_CLIENT_ID} \
      --env AWS_REGION=${AWS_REGION} \
      --volume ~/aws-lambda-rie:/aws-lambda \
      senzing/cognito-authorizer \
        /var/lang/bin/python -m awslambdaric cognito_authorizer.handler
  4. In a separate terminal window, call the lambda. Example:

    curl -v -X POST \
      http://localhost:9001/2015-03-31/functions/function/invocations \
      --data-binary @- << EOF
        {
          "RequestType": "Create",
          "ResponseURL": "",
          "StackId": "",
          "RequestId": "",
          "LogicalResourceId": ""
        }
    EOF

Make package for S3

Make sure that the python3 --version used to run the pip3 install command is the same as the python version seen in the AWS Lambda definition (i.e. the Runtime: parameter). If not the python packages may not be the correct version.

  1. Install dependencies. Example:

    cd ${GIT_REPOSITORY_DIR}
    pip3 install \
        --requirement requirements.txt \
        --target ./package
  2. Compress dependencies. Example:

    cd ${GIT_REPOSITORY_DIR}/package
    zip -r ../cognito-authorizer.zip .
  3. Add cognito_authorizer.py to compressed file. Example:

    cd ${GIT_REPOSITORY_DIR}
    zip -g cognito-authorizer.zip cognito_authorizer.py
  4. Upload cognito-authorizer.zip to AWS S3 in multiple AWS regions.

Advanced

Errors

  1. See docs/errors.md.

References

  1. PyPi - awslambdaric
  2. Creating a function with runtime dependencies