Secure AWS API Gateway with Cognito

Secure AWS API Gateway API with Cognito

This blog post will explore the steps to secure AWS API Gateway with AWS Cognito, empowering you to protect your APIs and their sensitive data.

In today’s digital terrain, ensuring your APIs’ security is essential. AWS API Gateway and Cognito provide a scalable and secure solution for managing and exposing APIs to external clients and enhancing security via robust user management and access control for your APIs. 


Understanding AWS API Gateway and AWS Cognito

Before diving into the implementation, let’s briefly explore the key components we’ll be working with.

What is Amazon API Gateway?

Amazon API Gateway is a fully managed service that makes it easy for developers to create, deploy, and manage APIs at any scale. It allows you to create RESTful APIs integrating various AWS services, including Lambda, DynamoDB, and others.

With API Gateway, you can control access to your APIs, monitor usage, and handle errors and caching.

What is Amazon Cognito?

Amazon Cognito User Pool is a fully managed user directory that provides a secure and scalable user sign-up and authentication solution for mobile and web applications. It allows developers to add user sign-up, sign-in, and access control to their applications quickly and easily.

With AWS Cognito User Pool, developers can create custom authentication workflows, choose from various sign-in methods like email, phone number, and social identity providers like Facebook, Google, and Amazon, and manage user profiles, attributes, and passwords. The service also provides features for multi-factor authentication, account verification, and password policies.

AWS Cognito User Pool integrates with other AWS services, including AWS Lambda, Amazon API Gateway, and Amazon S3, making it easy to build scalable and secure applications on AWS.

Additionally, it supports standards-based authentication protocols like OpenID Connect and OAuth 2.0, enabling developers to integrate with third-party identity providers and securely share user identity data between applications.


Architecture Flow for AWS API Gateway and AWS Cognito Integration

Below is the architecture diagram for AWS API Gateway and Cognito Integration

Secure AWS Api Gateway with AWS Cognito architecture diagram
Architecture Flow of Integration
  • A client sends an API request: The client, such as a web or mobile application, sends an HTTP/HTTPS request to the API Gateway to access a protected resource.
  • API Gateway checks for authorization: The API Gateway examines the incoming request and validates whether it requires authorization. If the request requires authorization, the API Gateway proceeds to the next step.
  • API Gateway invokes AWS Cognito: The API Gateway invokes AWS Cognito, a fully managed user authentication and authorization service provided by AWS.
  • AWS Cognito validates the request: AWS Cognito receives the request from the API Gateway and validates it based on the provided access token or other credentials. It verifies the token’s authenticity, checks its expiration, and verifies the signature.
  • Token validation response: AWS Cognito responds to the API Gateway, indicating whether the provided access token is valid.
  • API Gateway makes authorization decisions: Based on the response from AWS Cognito, the API Gateway makes an authorization decision. The API Gateway allows the request to proceed if the token is valid and the user has the required permissions. Otherwise, it returns an authorization error response.
  • API request processing: If the request is authorized, the API Gateway forwards the request to the backend service responsible for processing the request.

Below is a summary of the steps we are going to perform

  1. Create an AWS Cognito User Pool and add an app client.
  2. Create a REST API in the API gateway with a GET Method: For this tutorial, we are mocking the GET API. API Gateway allows you to mock and send static data for development purposes.
  3. Create and Configure API with the Authorizer: We will create Amazon API Gateway Cognito Authorizer and configure the API methods created in Step 2 
  4. Test the API: Once you have configured your authorizer and protected your API methods, you can test your API by sending requests with valid and invalid authentication tokens.

Below are a few prerequisites for this tutorial:

  1. AWS Account 
  2. Knowledge of AWS API Gateway, AWS Cognito services
  3. Knowledge of the OAuth2 protocol

Step 1: Create an AWS Cognito User Pool and add an App Client

  • Log in to your AWS Management Console, navigate to the AWS Cognito service, and click “Create a User Pool.”
Create a Cognito User Pool at AWS Console
Create a User Pool at AWS Cognito
  • Choose the provider type you want to configure for your client for signup and sign-in options you want to allow for your users, such as email, phone number, or social identity providers like Facebook or Google. 
  • Configure your password policies and multi-factor authentication options, such as SMS or Account recovery.
Configuring password policy for AWS Cognito's user pool
Configure Password Policy for User Pool
  • Configure account recovery settings for a user
Configure Cognito User Pool Account Recovery
Set up account recovery for the user pool
  • Keep Attribute verification and user account confirmation, Self-service signup to default settings.
configure self ign up configuration for user pool
  • Define user attributes, such as username, email, and phone number, and customize the attribute validation rules.
  • Customize your email and SMS templates for user communication, such as welcome emails and verification codes.
  • Provide your User Pool Name, and check the box for Use the Cognito Hosted UI to utilize the Cognito UI Signup/Sign-In Page.
  • Under Domain, select Use Cognito Domain and provide the domain prefix.
Configure Hosted Zone for user Pool
Configure Hosted Zone for user Pool
  • To add an initial client, select Public Client.
    • The Public client is the User Facing Apps.
    • Confidential Client – Clients Services running in your environment and no user-facing involved
    • Other: if you want to implement your custom OAuth grants etc
Add API Client to AWS Cognito Service
Add API Client to Service
  • It would help if you did not generate the Client Secret for Public Clients, as User-Facing apps must not have sensitive data. 
  • Provide the Callback URL where you want to get your access token returned.
  • Expand Advance app Client Settings, and
    • Keep everything default for now.
    • Ensure ‘Cognito user Pool’ is selected for an Identity provider.
    • Select Implicit Grant for ‘OAuth 2.0 grant types.
Configure App Client Setting for User Pool
Advance APP Client Settings
Configure Oauth2 Grant for app Client
Select OAuth2 Grant for User Pool
  • Review your settings and create your Cognito User Pool. 

Step 2: Create REST Endpoint at AWS API Gateway

  • Log in to your AWS Management Console, navigate to the API Gateway service, and click the “Create API” button.
Create a REST API at AWS API Gateway Console
Create a REST API at AWS API Gateway
Create resource for REST API for API Gateway
Create a resource for REST API for API Gateway
  • Select the “REST API” option and choose
    • Protocol – For this tutorial, select REST
    • Select ‘New API’ for the Create a New option.
    • Provide the API Name, Description, and the type of endpoint you want to create (e.g., Edge-optimized, Regional, or Private).
  • Click “Create API” to create your new API.
  • Click on Action Drop Down and select “Create Resource” to create a new resource for your endpoint.
  • Enter a name for your resource and click “Create Resource.” 
Set up GET Method for Resource
  • Click on “Create Method” and select the HTTP method you want to use (GET, POST, PUT, DELETE, etc.).
    • Create GET Method
    • Select Integration Type as ‘Mock’ since we will mock the endpoint without real integration.
    • Click Save
Create Model for REST API at AWS API Gateway
Create Model for REST API at AWS API Gateway
  • From Left Navigation Bar, navigate to Modals. Click on “Create” to create a mock modal.
    • Model Name: SuccessModal
    • Content-Type: application/json
    • For Model Schema copy the below content
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "Success Schema",
  "type" : "object",
  "properties" : {
    "message" : { "type" : "string" }
  }
}

This is a JSON Schema for Success Modal where we return a success message if everything works fine.

  • Navigate back to the Method we created earlier and click Integration Response.
  • Expand the existing 200 response and expand Mapping Template. Click on Adding Mapping template
    • Add application/json in the text box
    • From Generate Template Dropdown select SuccessModal and copy the below content
#set($inputRoot = $input.path('$'))
{
  "message" : "User Authenticated. Access to API Gateway Granted"
}
Add message to sucess modal for resources created for REST API at API Gatway
Add message using the Sucess Modal
  • Click “Save” to save your changes.
  • Deploy your API to a stage, such as “prod” or “dev”, by clicking on the “Actions” dropdown menu and selecting “Deploy API”.
  • Choose the stage you want to deploy to and click “Deploy”.
Deploy REST API to AWS API Gateway
Deploy API to AWS API Gateway

Step 3: Create and Configure API Gateway Authorizer

  • Open the API Gateway console and select your API.
  • Select the “Authorizers” option from the left-hand menu.
  • Click the “Create New Authorizer” button.
  • Choose Amazon Cognito User Pool as an authorizer. From the Drop down select the User pool you have created
  • Provide the name and in Token Source add ÔÇťAuthorizationÔÇŁ
  • Save the authorizer configuration.
Add Authorizer to API Gateway
Add Authorizer to API Gateway
  • Navigate to the Resources section to the GET request created
  • Click the Method Request link. 
  • Choose MyAuthorizer as the Authorization setting. If it is not available as an option to choose from, refresh the page first. And do not forget to click the v-icon, otherwise, the change is not saved.
Add Authorizer to API GET endpoint to API Gateway
Add Authorizer to API GET endpoint to API Gateway
  • Deploy the API again to implement the changes

Step 4: Test the Integration

We need to execute the below steps to test our endpoint.

  • Navigate to the AWS Cognito and open the App client created earlier.
  • Scroll down and click on View Hosted UI. 
  • Sign in with user credentials created earlier. You are redirected to the callback URL you configured, which now contains some extra parameters. Copy the value of the ID token.
  • Navigate to the API Gateway service to your API. Select the GET method of the stage you deployed in the Stages section. 
Deployed GET Endpoint at API Gateway
Deployed GET Endpoint at API Gateway
  • Here you will find the URL of your stage. Copy the URL and paste it to POSTMAN, and in the header, add the copy value of the token under the header “Authorization.”
  • You will get Success Response along with the message we created
Success Authentication at API Gateway API using AWS Cognito User Pool
Success Authentication at API Gateway API using AWS Cognito User Pool
  • You will get an access denied message if you do not provide the token or an incorrect token.
Denied Authentication at API Gateway API using AWS Cognito User Pool
Denied Authentication at API Gateway API using AWS Cognito User Pool

Conclusion

Congratulations! You have successfully configured and tested the API Gateway to only serve content to authenticated users in the Cognito User Pool.

Thank you for taking the time to read this article. If you have any questions or suggestions, please feel free to comment below.


AWS Community Builder | Software Architect @ Gigaforce | Serverless | Aspiring Entrepreneur | Quirky Introvert­čśé

Leave a Reply

Your email address will not be published. Required fields are marked *