Secure AWS API Gateway API with Cognito Himanshu Gupta, May 11, 2023May 11, 2023 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 CognitoBefore 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 IntegrationBelow is the architecture diagram for AWS API Gateway and Cognito IntegrationArchitecture Flow of IntegrationA 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 performCreate an AWS Cognito User Pool and add an app client.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.Create and Configure API with the Authorizer: We will create Amazon API Gateway Cognito Authorizer and configure the API methods created in Step 2 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:AWS Account Knowledge of AWS API Gateway, AWS Cognito servicesKnowledge of the OAuth2 protocolStep 1: Create an AWS Cognito User Pool and add an App ClientLog in to your AWS Management Console, navigate to the AWS Cognito service, and click “Create a User Pool.”Create a User Pool at AWS CognitoChoose 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.Configure Password Policy for User PoolConfigure account recovery settings for a userSet up account recovery for the user poolKeep Attribute verification and user account confirmation, Self-service signup to default settings.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 PoolTo 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 involvedOther: if you want to implement your custom OAuth grants etcAdd API Client to ServiceIt 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, andKeep everything default for now.Ensure ‘Cognito user Pool’ is selected for an Identity provider.Select Implicit Grant for ‘OAuth 2.0 grant types.Advance APP Client SettingsSelect OAuth2 Grant for User PoolReview your settings and create your Cognito User Pool. Step 2: Create REST Endpoint at AWS API GatewayLog 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 GatewayCreate a resource for REST API for API GatewaySelect the “REST API” option and chooseProtocol – For this tutorial, select RESTSelect ‘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 ResourceClick on “Create Method” and select the HTTP method you want to use (GET, POST, PUT, DELETE, etc.).Create GET MethodSelect Integration Type as ‘Mock’ since we will mock the endpoint without real integration.Click SaveCreate Model for REST API at AWS API GatewayFrom Left Navigation Bar, navigate to Modals. Click on “Create” to create a mock modal.Model Name: SuccessModalContent-Type: application/jsonFor 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 templateAdd application/json in the text boxFrom Generate Template Dropdown select SuccessModal and copy the below content#set($inputRoot = $input.path('$')) { "message" : "User Authenticated. Access to API Gateway Granted" }Add message using the Sucess ModalClick “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 API to AWS API GatewayStep 3: Create and Configure API Gateway AuthorizerOpen 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 createdProvide the name and in Token Source add “Authorization”Save the authorizer configuration.Add Authorizer to API GatewayNavigate to the Resources section to the GET request createdClick 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 GatewayDeploy the API again to implement the changesStep 4: Test the IntegrationWe 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 GatewayHere 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 createdSuccess Authentication at API Gateway API using AWS Cognito User PoolYou 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 PoolConclusionCongratulations! 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. Please leave this field emptyStay Up-to-Date with Our Weekly Updates. We don’t spam! Read our privacy policy for more info.Check your inbox or spam folder to confirm your subscription.FacebookTweetPinLinkedInEmail AWS Cloud Cloud Computing amazon cognitoaws api gatewayaws cognitocloud computingREST API