Secure REST API using AWS Cognito User Pools

by David García

June 25, 2019

This example adds authentication to a REST API provided by AWS API Gateway. After setting up this example, AWS Cognito will be able to guard requests between registered and guest users.

Quick Notes
Secure REST API using AWS Cognito User Pools

Solution Details

This recipe uses the serverless framework which creates and deploys the required components to manage users using Cognito. A user pool is created where users register with their email address and will require the password to have a minimum length of 6 characters, including an uppercase and a number. API calls that can only be accessed by registered users can add the Cognito User Pool as an authorizer so that the calls are made through Cognito. For example, the RegisteredHandler lambda function has an authorizer attached to it in the serverless.yml file.

After creating the user pools, any front end source can start using Cognito to log in and sign up users.


Prerequisites Setup AWS Credentials
Make sure you have AWS access key and secrete keys setup locally, following this video here

Download the code

git clone

Deploy to the cloud

cd serverless-cognito

serverless deploy --stage beta

Frontend Setup

To use your own frontend, we need to manually configure some details. In the Cognito Dashboard, select the User Pool and follow the steps below:

  • Select "App client settings", enable Cognito User Pool as a provider and enter the callback and sign out URLs. Select "Implicit grant" as allowed OAuth flow and tick all the scopes

  • Select "Domain name" and create one


To test the end to end flow,

  • Open a web browser and go to https://<your_domain>/login?response_type=token&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>

  • After loging in successfully, you'll be redirected to your calback URL with id_token in the query string

  • Put id_token in the Authorization HTTP header when submitting requests to the API


To remove the stack, run the following command:

serverless remove --stage beta
source code