Building RESTful APIs — Serverless — Part 1 of 3 —AWS Cognito User Pools
Modern applications are running on top of several managed cloud micro-services to achieve real time scalability and high availability without paying for idle resources which was an issue with traditional architecture behind an application where we needed to consider sudden traffic and other factors before provisioning servers that sometimes leads to over-provisioning or under-provisioning. Scalability is a real challenge in traditional architecture.
What about an application where our user and authentication module will be taken care of by a service whole sole purpose is user profiling and authentication only and can scales to support millions of users, REST API endpoints for mobile and web applications by another service that is capable of throttling, validating and securing APIs with enormous scaling capacity and then writing only business logic on functions rather than provisioning a server for execution ? This is what we are going to accomplish in this tutorial series.
In this 3 part tutorial series we will develop below sample RESTful APIs -
1. Sign Up API
2. Sign In API
3. Refresh Token API
4. Private API (requires authentication)
and to accomplish that with serverless architecture we are going to use following microservices offered and managed by AWS.
1. AWS Cognito User Pool (For User and authentication management)
2. AWS Lambda Function (To run code that receives users request payload through API Gateway and communicate with AWS Cognito and other microservices as required)
3. API Gateway (To create RESTful API endpoints, validating incoming requests etc., authorizing private APIs using Cognito authorizer)
So, let’s start configuring and building these APIs step by step -
Configuring and Setting Up Amazon Cognito User Pool
As stated in Cognito dashboard -
“Amazon Cognito offers user pools and identity pools. User pools are user directories that provide sign-up and sign-in options for your app users.”
To set up cognito user pools first we need to login into AWS console. Under Services > Security, Identity, & Compliance sub-menu you will find Cognito. Click this service and you’ll be redirected to cognito dashboard.
Click Manage User Pools and then click Create a user pool button.
Upon clicking you’ll be asked to give a name to your user pool. Here I used tutorials-user-pool, for example. You are free to use any name that is easily identifiable by you.
Click Step through settings. You will be asked on “How do you want your end users to sign in?” In this tutorial, we will use email address as “username”. However you are free to use phone number or username also as “username” for Sign In and Sign Up Purpose.
“Which standard attributes do you want to require?” section will provide you a list of standard attributes for user profiles from which you can choose required attributes for Sign Up. Here we are going to choose name, phone number. You are free to add your own custom attributes if required.
Click Next step. Policies section deals with password strengths, sign up settings and temporary password expiration policy. We want our users to sign themselves us and we will keep the password strength policy exactly as it is to force user to use a strong password.
Click Next step for MFA and verification section that deals with Multi factor authentication and email and/or phone verification. For the simplicity of this tutorial we are disabling both (MFA — off, Verification — no verification).
Click Next Step for Message Customizations tab. As we turned off MFA and verification in previous step we are going to leave this page as it is.
Click Next step for Tags settings. If you want to add tag to user user pool feel free to add one or more tags. It’s optional. However we are using a tag “Name” : “Tutorial user pool” as example.
Click Next step for Devices section. We are leaving it as it is for this tutorial.
Click Next Step for App clients section. If you want to give some App access to your user pool click Add an app client button. An unique client id and client secret key will be given to this App client to access this user pool. Give a name to this App client, keep or change the refresh token expiration as it is, check Generate client secret checkbox and as we want our users to sign themselves up and in also check Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH) checkbox.
If you want to give this App client fine grained read and write permission to attributes of this user pool click “Set attribute read and write permissions”. Here we are going to leave it as it is. Click Create app client button.
Click Next step for Triggers section. What this section do ? As stated -
“You can make advanced customizations with AWS Lambda functions. Pick AWS Lambda functions to trigger with different events if you want to customize workflows and the user experience.”
Here we need to configure one trigger for us. As we disabled verification in earlier settings we need to confirm a user during signup using a Pre sign-up lambda trigger. We will cover that later in this tutorial.
Click Next step. Under Review section crosscheck everything that we have configured so far. Then click Create pool button to finish creating your user pool.
Wait for a while and your user pool is created then.
User pool creation is done. Now, we will configure Pre Sign-up trigger with a Lambda function.
“The pre sign-up Lambda function is triggered just before Amazon Cognito signs up a new user. It allows you to perform custom validation to accept or deny the registration request as part of the sign-up process.”
To create a Lambda function let’s go to Services > Compute > Lambda from top menu.
On Lambda Dashboard click Create function, select Author from scratch. Under Basic Information give that function a name, for example: preSignupTrigger, select Python 3.6 as Runtime (as we will use Python in this tutorial) and then leave rest as default. Then click Create function. The function will be created then. Once it’s created under Function code section there will be a code editor with a file opened lambda_function.py (by default). Remove existing code snippet and paste below code into that file and then click Save.
From above code snippet, we can see that autoConfirmUser
, autoVerifyEmail
, autoVerifyPhone
has been set to True
. As we disabled verification in earlier cognito setup stage (which is not recommended though) we have set autoVerifyEmail and autoVerifyPhone to True.
You can define your own validation logic to set whether autoConfirmUser
should be True or False.
To know more about Pre sign-up trigger visit this link.
We’re done with Lambda console for now. Now let’s go back to Cognito dashboard from services menu. Click tutorials-user-pool. In sidebar, under General settings click Triggers tab. Under Pre sign-up section, select newly created Lambda function i.e. “preSignUpTrigger” as a value of Lambda function field. Scroll down to bottom and click Save Changes.
Finally, we are done with Part 1 of our 3 part series. In this part we created a new cognito user pool, configured it for authentication, created and configured a pre sign-up lambda function.
In next tutorial i.e. Part 2 we will create 4 separate Lambda functions for SignUp, SignIn, RefreshToken and for a Private API.
Part 2: https://medium.com/@mahfuzcse12/building-restful-apis-part-2of-3-serverless-aws-lambda-974a24fbfb12