API Gateway Authorizer Function for Auth0 or AWS Cognito using the JWKS method.

This is an example of how to protect API endpoints with Auth0 or AWS Cognito using JSON Web Key Sets (JWKS) and a custom authorizer lambda function.

Custom Authorizers allow you to run an AWS Lambda Function via API Gateway before your targeted AWS Lambda Function is run. This is useful for Microservice Architectures or when you simply want to do some Authorization before running your business logic.

Use cases

  • Protect API routes for authorized users
  • Rate limiting APIs
  • Remotely revoke tokens

Setup

  1. npm install json web token dependencies

  2. In auth.js replace the value of iss with either your Auth0 iss or AWS Cognito ISS. Make sure the iss url ends in a trailing /.

/* auth.js */
// Replace with your auth0 or Cognito values
const iss = "https://<url>.com/";
  1. Deploy the service with sls deploy and grab the public and private endpoints.

Test Authentication:

  • Test with Postman: Make a new GET request with the Header containing "Authorization" with the value being "bearer <id_token>" for your api/private url.
  • Test using curl:
    curl --header "Authorization: bearer <id_token>" https://{api}.execute-api.{region}.amazonaws.com/api/private