A modern, ES6-friendly Lambda Authorizer ready for integration with Serverless Framework and Auth0.
Based on the serverless/examples/aws-node-auth0-custom-authorizers-api example.
- Test front-end application
- Private endpoint for testing
- Public endpoint for testing
- ES6-friendly
sls create --name auth-service --template-url https://github.com/codingly-io/serverless-auth0-authorizer
cd auth-service
npm install
This file will contain your Auth0 public certificate, used to verify tokens.
Create a secret.pem
file in the root folder of this project. Simply paste your public certificate in there.
We need to deploy the stack in order to consume the private/public testing endpoints.
sls deploy -v
To make sure everything works, send a POST request (using curl, Postman etc.) to your private endpoint.
You can grab a test token from Auth0. Make sure to provide your token in the headers like so:
"Authorization": "Bearer YOUR_TOKEN"
You should be good to go!
This is very useful in a microservices setup. For example, you have an Auth Service (this service) which owns anything auth/user-related, and a bunch of other services that require user authorization. Fear not, it is very easy to make your authorizer work anywhere else in your AWS account.
When defining your Lambdas in other services, simply define the authorizer
as well and provide the ARN of your auth
function (can be found in the AWS Console or via sls info
).
functions:
someFunction:
handler: src/handlers/someFunction.handler
events:
- http:
method: POST
path: /something
authorizer: arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:sls-auth-service-draft-dev-auth
If everything was set up correctly, all incoming requests to your someFunction
Lambda will first be authorized. You can find the JWT claims at event.requestContext.authorizer
.
Use the following curl command:
curl --location --request POST 'https://YOUR_AUTH0_DOMAIN/oauth/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=YOUR_AUTH0_CLIENT_ID' \
--data-urlencode 'username=YOUR_USERNAME' \
--data-urlencode 'password=YOUR_PASSWORD' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'scope=openid'