API Gateway Custom Authorizer Function + Auth0
This is an example of how to protect API endpoints with auth0, JSON Web Tokens (jwt) and a custom authorizer lambda function.
Custom Authorizers allow you to run an AWS Lambda Function before your targeted AWS Lambda Function. 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
Setup
-
You must have Python 3! Once you do, run
pip install -r requirements.txtto install Python web token dependencies -
Install Docker. Why Docker? Because it's the only way to ensure that the Python package that is created on your local machine and uploaded to AWS will actually run in AWS's lambda containers.
-
Setup an auth0 client and get your
client idandclient secretsfrom auth0. -
Plugin your
AUTH0_CLIENT_IDandAUTH0_CLIENT_SECRETin a new file calledsecrets.json. These will be used by the JSON web token decoder to validate private api access. -
Copy the
public_key-examplefile to a new file namedpublic_keyand follow the instructions in that file -
Deploy the Lambda Authorizer to AWS with
make deployand grab the public and private endpoints from theendpoints:section of themakecommand output -
Plugin your
AUTH0_CLIENT_ID,AUTH0_DOMAIN, and thePUBLIC_ENDPOINT+PRIVATE_ENDPOINTfrom aws in top of thefrontend/app.jsfile.
/* frontend/app.js */
// replace these values in app.js
const AUTH0_CLIENT_ID = 'your-auth0-client-id-here';
const AUTH0_DOMAIN = 'your-auth0-domain-here.auth0.com';
const PUBLIC_ENDPOINT = 'https://your-aws-endpoint-here.amazonaws.com/dev/api/public';
const PRIVATE_ENDPOINT = 'https://your-aws-endpoint-here.us-east-1.amazonaws.com/dev/api/private';
- You can either run your frontend locally or deploy your frontend to host of your choosing. However in either case, make sure to configure the
Allowed Callback URLandAllowed Originsin your auth0 client in the auth0 dashboard. An example of how to run your frontend locally:
cd frontend;
python -m http.server
Custom authorizer functions
Custom authorizers functions are executed before a Lambda function is executed and return an Error or a Policy document.
The Custom authorizer function is passing an event object to API Gateway as below:
{
"type": "TOKEN",
"authorizationToken": "<Incoming bearer token>",
"methodArn": "arn:aws:execute-api:<Region id>:<Account id>:<API id>/<Stage>/<Method>/<Resource path>"
}
You will have to change this policy to accommodate your needs. The default reply provided, will only authorize one endpoint!
Frontend
The frontend is a bare bones vanilla javascript implementation.
You can replace it with whatever frontend framework you like =)
If you do implement in another framework, please consider adding it our growing list of examples!
API calls are made with the browser's native fetch api.