In this blog, we’ll look at how to secure AWS API Gateway endpoints using Cognito User Pools and a JWT authorizer. Authorizers, as described by API Gateway, are services that provide or deny API access to clients depending on a variety of parameters, including authenticated users, permissions, IP addresses, and so on. JWT Authorizers are a new form of Authorizer that uses JSON Web Tokens (JWTs) to offer access control to your API endpoints, as the name implies. JWT Authorizers are based on the OpenID Connect (OIDC) document and the OAuth 2.0 protocol, which are industry standards. Requests to your API will require an access token, which the Authorizer will check once enabled. We’ll look at how to add JWT authorizers to routes to protect them from unauthorized access.
In this blog, we will cover:
- What is Amazon Cognito?
- How does it work?
- Components of Amazon Cognito
- Benefits of AmazonCognito
- Common Use cases
- Features of Amazon Cognito
- Pricing
- Customers using Amazon Cognito
- Hands-on
- Conclusion
What is Amazon Cognito?
Amazon Cognito is a web service that manages user identification and authentication. It synchronizes the user data pool across many Amazon Cloud devices. Amazon Cognito enables sign-in with social identity providers such as Apple, Facebook, Google, and Amazon, as well as enterprise identity providers through SAML 2.0 and OpenID Connect, and is scalable to millions of users.
How does it work?
Amazon Cognito lets you easily add users to your mobile and web apps by including sign-in screens and authentication functions. Amazon Cognito is a critical component of AWS application development.
There are three basic features of Amazon Cognito:
- User management
- Authentication
- Synchronization
For all of your users, Cognito handles security, authorization, and synchronization for your user management process across devices.
External identity providers, such as Facebook, Twitter, Google, LinkedIn, and other social identity providers, can also be utilized to authenticate your users with Cognito.
Cognito may also be used to verify identities in any solution that follows the SAML 2.0 standard. These authorized users can be given temporary security credentials with limited rights to safely access your AWS services.
Components of Amazon Cognito
Cognito is divided into two primary sections: User Pools and Identity Pools.
User Pools: A user directory for authentication (identity verification) that aids in the creation and maintenance of user sign-up and sign-in to online and mobile apps. It also has improved security features including multi-factor authentication (MFA) with email or phone number verification. It’s also set up using AWS Lambda, which allows customers to modify validation and registration routines.
Identity Pools: It allows us to provide our users access to other AWS services without having to re-enter their credentials. User Pools and Identity Pools are versatile in Amazon Cognito and may be utilized independently or jointly.
Benefits of Amazon Cognito
Secure and scalable user directory: Amazon constructs and manages the user pool for your application, making it secure and scalable. The user directory is extremely scalable, with the ability to handle millions of people. It’s also simple to set up. Each user’s distinct identity can be generated. You may utilize the directory to allow your users to sign in to your mobile or online application using Amazon Cognito.
Social and enterprise identity federation: In addition to AWS Cognito, your users may sign in using a variety of social identity providers. Users can, for example, create a profile using Google, Facebook, or Apple login. Your users will have a faultless and painless experience as a result of this. You will have a record in your directory of whether the user creates their profile using any of the aforementioned techniques.
Standards-based authentication: Amazon Cognito User Pools is a standards-based Identity Provider that supports OAuth 2.0, SAML 2.0, and OpenID Connect as well as other identity and access management standards.
Security for your apps and users: Amazon Cognito enables multi-factor authentication and data encryption at rest and in transit for your apps and users. HIPAA-compliant, Amazon Cognito complies with PCI DSS, SOC, ISO/IEC 27001, ISO/IEC 27017, ISO/IEC 27018, and ISO 9001.
Access control for AWS resources: Amazon Cognito offers methods for controlling access to AWS resources from your app. You may create roles and assign users to them so that your app can only access the resources that each user has access to. Alternatively, you may utilize identity provider attributes in AWS Identity and Access Management permission policies to restrict resource access to users that fulfill certain attribute criteria.
Easy integration with your app: You can integrate Amazon Cognito to add user sign-in, sign-up, and access control to your app in minutes, thanks to a built-in UI and simple configuration for federating identity providers. You may personalize the user interface to make your company’s branding stand out during all user interactions.
Common Use cases
- It may also be used to implement AI using lambda expressions. When a user views a product, for example, a function can be called to display similar products.
- Access control to AWS services such as an S3 bucket is allowed only after user verification.
- To offer stronger security and provide confidence to its users, automatic email verification is required.
Features of Amazon Cognito
Built-in customizable UI: For user sign-up and sign-in, Amazon Cognito has a built-in, customized UI. To add user sign-up and sign-in pages to your apps, you may utilize the Amazon Cognito SDKs for Android, iOS, and JavaScript.
Advanced security features: You may enable advanced security features for your Amazon Cognito with only a few clicks. Amazon Cognito User Pools aid in the security of user accounts in your apps. These enable risk-based adaptive authentication as well as protection against credential compromise.
Apps directory for users: Amazon Cognito User Pools provide users access to a secure user directory. Because User Pools is a fully managed service, it’s simple to start up without worrying about server infrastructure. For users who join up directly and federated users who sign in using social and business identity providers, User Pools give user profiles and authentication tokens.
Pricing
You only pay based on your monthly active users (MAUs) if you utilize Cognito Identity to build a User Pool.
The overall quantity of data saved in the Amazon Cognito sync store and the number of sync operations executed determine Cognito Sync costs.
For the first 12 months, eligible AWS users get 10 GB of cloud sync storage and 1,000,000 sync operations per month as part of the AWS Free Tier.
Companies using Amazon Cognito
Hands-on
Any business that creates an API-based architecture must create a standard security layer around these APIs, essentially on the edge, to ensure that all APIs are secure. In this blog, we will see how to create a JWT authorizer, attach the same to the API route and create an AWS Cognito User Pool to allow people to sign up with their email address as their username and a password. Cognito confirms the registration by sending the user a code to the email address provided during sign-in, which the person will have to pass to the Amazon Cognito service.
After the user has been verified, they can log in with their username and password, and Cognito will return a one-hour token. The token can then be used in the header of HTTP GET requests to Amazon API Gateway, which will be configured to use the Cognito User Pool as a JWT authorizer. Any queries with Unauthorized messages will be rejected if the API gateway does not have a valid token. With a valid token, the API gateway will pass the request to a Lambda function that will then return the response that is to be displayed on hitting the API URL.
To implement this, we will do the following:
- Log in to the AWS console and navigate to the Lambda function dashboard.
- Create a new Lambda function with Python 3.8 as the Runtime.
- Configure the code editor to add the code based on your API requirement.
- Navigate to the Amazon API Gateway console and create an HTTP API.
- Attach the Lambda function as an integration to your API route.
- Navigate to the Amazon Cognito console and create a new user pool.
- Configure the User pool creation.
- Create an App client for your user pool.
- Create a new Cognito domain and check for its availability.
- Navigate to the API Gateway console and create and attach an authorizer.
- Configure the JWT Authoriser with the Amazon Cognito service.
- Configure the app client settings.
- Attach the authorizer to your API Gateway route.
- Open the Hosted UI.
- Sign up and get verified as a Cognito user.
- Test the JWT Authoriser by signing up and logging in and testing for the protection of the API route.
Login to your AWS account and search for the Lambda service. Click on it to navigate to the Lambda dashboard.
On the Lambda dashboard, click on Create function.
Select Author from scratch, enter a name for your function, select the runtime as Python 3.8.
Expand the Change default execution role, select a role if you have created a role for yourself, or let the AWS Lambda function create a new role by default. Click on the Create function once done.
On success, you will see the message as shown in the image below.
Scroll down and open the code editor. Enter the code for your API. For this blog, we are just returning a text from the Lambda function to experiment and test the JWT authorizer.
Now, in the search bar, search for the API Gateway service. Click on the service to navigate to its dashboard.
On the API Gateway dashboard, click on Create API to create a new HTTP API.
Click on Build for the HTTP API.
Choose an AWS Lambda function or an HTTP endpoint, then click Add integration.
For Name, enter a name for your API. Click on Next.
Here, you need to configure your routes based on your requirements.
We have updated the route as shown in the image below. Once done, click on Next.
In this step, you need to add a stage if needed like development and production.
Click on Add Stage to add a new stage. You can switch on and off the toggle if you need auto-deployment for your stage. Click on Next.
Once done, review all the configurations and click on Create.
If you are successful, you will see a notice similar to the one below.
Under stages, click on the Invoke URL to test if the API is invoking the Lambda function correctly.
In the left navigation pane, click on integrations. Over here you can change the lambda integrations based on your API requirements.
Now, search for the Amazon Cognito service.
Select Manage User Pools from the dashboard.
Click on Create a user pool.
Enter a name for your User pool. Click on Step through settings.
Over here, you can make the changes as per your requirements.
You can allow only the administrators to create and import users as per your requirements.
Click on App Clients in the left navigation pane. Click on Add an app client.
Enter a name for your app client.
Scroll down and change the configurations as shown in the image below. Once done, click on Create app client.
You will see your newly created app client on the dashboard.
Click on Review in the left pane.
Review all the configurations, scroll to the bottom, and click on Create pool.
You will see the notice as seen in the image below if you are successful.
In the left pane, select Domain name.
Enter a name for the domain and check its availability. Once done, click on Save Changes.
Now, navigate back to the API Gateway dashboard. Click on Authorizations in the left pane. Click on Create and attach an authorizer.
Select JWT as the type. Select a name for your authorizer. Let the Identity source be the same as it was by default.
Navigate to the Cognito dashboard and click on General settings. Copy the Pool Id.
Navigate back to the API Gateway console and in the Issuer URL, enter the following in the proper format with the required details:
Now, navigate to the Cognito dashboard and click on App clients. Copy the App client id.
On the API Gateway console, click on Add audience. Paste the client id in the text box.
Once done, you will see the JWT Auth attached to your API route.
Now, navigate to the API section. If you click on the URL, you will get a message saying ‘Unauthorized’. Copy the URL.
Navigate to the Cognito dashboard and click on App client settings.
Select Cognito User Pool, in the Callback URL(s) paste the API URL.
Select the Allowed OAuth Flows and Allowed OAuth Scopes as shown in the image below. Once done, click on Save changes.
Click on Launch Hosted UI.
Click on Sign up.
Enter the details. On success, click on Sign up and you will receive a verification code on the entered email.
Enter the verification code in the text box. Click on Confirm Account.
On successful sign-up, you will be navigated to your API that is protected with JWT. If you look at the URL, you will see a code. On successful login or sign up, you will see code as shown in the URL that allows you to authorize yourself and access the API.
Conclusion
In this blog, we saw how we can create an HTTP API and integrate it with the JWT Authoriser and the Lambda function that is invoked on invoking the API URL. We even saw how to configure a hosted UI with the needed authorization to protect the HTTP API via the JWT Authorisers. JWT Authorizers are a new form of Authorizer that uses JSON Web Tokens (JWTs) to offer access control to your API endpoints, as the name implies. We will discuss more use cases of JWT Authorisers via Amazon Cognito and its integration with other services in our upcoming blogs. Stay tuned to keep getting all updates about our upcoming new blogs on AWS and relevant technologies.
Meanwhile …
Keep Exploring -> Keep Learning -> Keep Mastering
This blog is part of our effort towards building a knowledgeable and kick-ass tech community. At Workfall, we strive to provide the best tech and pay opportunities to AWS-certified talents. If you’re looking to work with global clients, build kick-ass products while making big bucks doing so, give it a shot at workfall.com/partner today.