Securing API Gateway using Amazon Cognito User Pools

2022.03.05

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

API

It stands for Application Program interface which helps in connection of two applications, computers, or between computer programs to talk to each other. It is used to access data, server software, or other applications and has been around for some time. Each time anyone uses a particular app for weather updates or good restaurants API’s is used.

API Gateway

A fully managed service that makes developers easily create, publish, maintain, monitor, and secure APIs at any scale. Using API Gateway can create Restful APIs and WebSocket APIs which have real-time two-way communication applications. It is a front door for applications to access data, business logic, or functionality from your backend services.

Amazon Cognito

It is an Amazon Web Service that controls user authentication and access for mobile applications on internet-connected devices. It is a service that saves and synchronizes end-user data. It enables an application developer to focus on writing code and leave the leave back end infrastructure in its hands.

Refer to the below blog to know how to secure API Gateway using Lambda Authorizer

Demo

In AWS console open Amazon Cognito and click on manage user pools Now click on create a user pool Give a Pool name, click review defaults and click create pool In side bar click app clents, add an app client, give a name and click create app client In the app client setting give the callback URL, signout URL, also make changes shown in the below diaghram and click save changes Enter an appropriate Domain name and click save changes In the client app settings click on launch hosted URL Click on sign up and create a user In a New tab open the AWS console and go to AWS Lambda and create a function with below specifications with no change in the default code. Back to AWS Console got the API Gateway and build a REST API Now creating the resource by following the below steps Create the method by following the below steps Now testing the GET method If it's working as intended Now Deploying the API and checking the invoke URL with "/transactions" created above in resources. Going back to Cognito client app settings, clicking hosted URL and in URL change the "code" to "Token" which will be used in the later section of the blog. From the above URl you can separate ID Token and Access Token. Have a check of these as they will be used in later section. The above gateway can be accessed by anyone in the world in order to restrict the access follow the below steps for adding an authorizer and testing the authorizer Paste the above Token ID in the below section Now attaching the Authorizer to API by following the below steps Now Deploying the API and copying the Invoke URl to a new tab As seen above it has resulted in unauthorized access now posting the Invoke URL into Postman from the above access token to access the API Gateway