User login with Amazon Cognito, Amazon API Gateway, and AWS Lambda

Banavalikar
4 min readJul 11, 2022

--

Creating a login page with Amazon Cognito, Amazon API Gateway, and AWS Lambda is a great way to add secure authentication to your web application. In this article, I will walk through the process of creating a login page using these AWS services and provide you with sample code to get started.

Prerequisites

Before we dive into the code, you will need to have an AWS account and have some familiarity with the AWS Console. You will also need to have the AWS CLI installed on your machine.

Step 1: Create a Amazon Cognito User Pool

The first step in creating a login page is to create a Amazon Cognito User Pool. A User Pool is an Amazon Cognito user directory that allows you to add sign-up and sign-in functionality to your application. Here are the steps to create a Amazon Cognito User Pool:

  1. Open the Amazon Cognito console at https://console.aws.amazon.com/cognito/.
  2. Choose Manage User Pools, and then choose Create a user pool.
  3. Enter a name for your user pool, and then choose Review defaults. The default settings are fine for this tutorial.
  4. Choose Create pool.

Step 2: Create a AWS Lambda Function

Next, we will create a AWS Lambda function to handle the authentication logic. This function will be responsible for validating the user’s credentials and returning a token if the credentials are valid. Here are the steps to create a AWS Lambda function:

  1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/.
  2. Choose Create function.
  3. Enter a name for your function, and select Python 3.8 as the runtime.
  4. Choose Create function.
  5. Copy the following code into the editor:
import boto3
import json

cognito = boto3.client('cognito-idp')
def lambda_handler(event, context):
username = event['username']
password = event['password']
user_pool_id = 'your-user-pool-id'
client_id = 'your-client-id'
response = cognito.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password
},
ClientId=client_id
)
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps(response)
}
  1. Replace ‘your-user-pool-id’ and ‘your-client-id’ with the appropriate values from your Amazon Cognito User Pool.
  2. Choose Deploy.

Step 3: Create an Amazon API Gateway

Now we will create an Amazon API Gateway to expose our AWS Lambda function as a REST API endpoint. Here are the steps to create an Amazon API Gateway:

  1. Open the Amazon API Gateway console at https://console.aws.amazon.com/apigateway/.
  2. Choose Create API.
  3. Choose REST API and then choose Build.
  4. Enter a name for your API and choose Create API.

Step 4: Create a Resource and Method

Next, we will create a resource and method in our Amazon API Gateway to handle the login request. Here are the steps to create a resource and method:

  1. In the Amazon API Gateway console, select the API that you just created.
  2. Choose Create Resource and enter a name for your resource.
  3. Choose Create Resource.
  4. With your resource selected, choose Create Method and choose POST.
  5. In the Integration Type section, choose AWS Lambda Function.
  6. Choose Use AWS Lambda Proxy integration and select the region where your AWS Lambda function is located.
  7. Enter the name of the AWS Lambda function that you created earlier and choose Save.

Step 5: Enable CORS

To enable Cross-Origin Resource Sharing (CORS), we will need to add some headers to the Amazon API Gateway. Here are the steps to enable CORS:

  1. Select the resource that you just created.
  2. Choose Actions, and then choose Enable CORS.
  3. In the Access-Control-Allow-Origin header field, enter ‘*’.
  4. Choose Enable CORS and replace the existing resources.

Step 6: Deploy the API

Finally, we will deploy the API so that it is publicly accessible. Here are the steps to deploy the API:

  1. With your API selected in the API Gateway console, choose Actions, and then choose Deploy API.
  2. Choose the Deployment stage and then choose Deploy.

Step 7: Test the Login Page

Now that our API is deployed, we can test the login page by sending a POST request to the Amazon API Gateway endpoint with the user’s credentials. Here is some sample code for a basic HTML login page that sends a POST request to the Amazon API Gateway endpoint:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Login</button>
</form>
<script>
const form = document.querySelector('#login-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const username = form.elements.username.value;
const password = form.elements.password.value;
const response = await fetch('your-api-gateway-endpoint', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
});
</script>
</body>
</html>

Replace ‘your-api-gateway-endpoint’ with the URL of your Amazon API Gateway endpoint. When the user submits the form, the JavaScript code sends a POST request to the Amazon API Gateway with the username and password in the request body. The AWS Lambda function then validates the user’s credentials and returns a token if the credentials are valid.

Congratulations, you have now created a login page with Amazon Cognito, Amazon API Gateway, and AWS Lambda! This is just a basic example, but you can extend this code to include features like password reset, email verification, and more.

--

--

No responses yet