A Comprehensive Guide to Passwordless Login with AWS Cognito and Amplify — Backend Guide

  • Sat Jun 22 2024
  • Jazim Abbas

If you’d like to explore the code, I’ve created a repository on GitHub where you can view it in detail.

This is a two-part series. I can’t cover everything in just one article, so I’ve broken it down into two parts:

I’ll be using AWS Cognito, AWS Amplify, and AWS SNS to send SMS messages to recipient phone numbers. This will be a completely automated process, allowing you to easily set up using AWS Amplify CI/CD. Another approach involves setting up all the AWS resources manually using the AWS Console. However, every time you make a change, you would need to go to the AWS Console and update it manually, which could introduce errors. Additionally, if you ever need to change the AWS Account, you would have to set up everything (all resources) from scratch, which is NOT RECOMMENDED.

Introduction

Remembering passwords can be a hassle, especially for those rarely used ones. Like many, you’re likely familiar with the “forgot password” link or button on websites and apps.

While solutions like password managers exist, password-based security isn’t always secure or user-friendly. Common bad practices include using short or easily guessable passwords, and reusing passwords across multiple sites and apps.

Alternatives to password-based login, such as fingerprint scans or facial recognition, aren’t always practical.

Amazon Cognito offers another option. What if logging in didn’t require entering a password, but instead, the website or app sent a temporary one-time login code via email, SMS, or push notification? Simply retrieve the code, enter it, and you’re in. It’s akin to a “forgot password” process, but simpler and quicker, without the implication that you forgot your password.

With Amazon Cognito user pools, you can create custom authentication flows. In this blog post, we demonstrate how by providing a sample implementation of a passwordless authentication flow that sends a one-time login code to the user’s phone number.

Solution Overview

The passwordless authentication solution leverages an Amazon Cognito user pool and a pair of Lambda functions, which work together to implement the custom authentication flow. Additionally, Amazon Simple Notification Service (Amazon SNS) is utilized for sending text messages containing the one-time login codes. The sign-in process is facilitated through custom UI pages developed using React App.

The following steps outline the process for the solution:

  1. The user enters their phone number on the custom sign-in page, which forwards it to the Amazon Cognito user pool.
  2. The user pool triggers the “Define Auth Challenge” Lambda function, responsible for determining the appropriate custom challenge to create.
  3. Subsequently, the user pool invokes the “Create Auth Challenge” Lambda function, which generates a secret login code and dispatches it to the user’s phone via AWS SNS.
  4. The user receives the secret login code on their phone and inputs it on the custom sign-in page, which forwards it back to the user pool.
  5. The user pool then calls the “Verify Auth Challenge Response” Lambda function, tasked with validating the code entered by the user.
  6. Upon successful code verification, the user pool again invokes the “Define Auth Challenge” Lambda function, confirming that the challenge has been adequately addressed and no further challenges are required. It responds to the user pool with ‘issueTokens: true’, indicating successful authentication. Subsequently, the user pool sends the user valid JSON Web Tokens (JWTs) in response.

Setup AWS Amplify CLI

To begin, you’ll need to set up AWS Amplify. Ensure you have at least Node.js v14.x installed. Next, globally install the AWS Amplify CLI by executing the following command:

npm install -g @aws-amplify/cli

Once the Amplify CLI is installed successfully, proceed to set up the CLI locally to run commands. Use the following command for local configuration:

amplify configure

You also have the option to configure the CLI manually. However, I won’t cover this topic here as it’s beyond the scope of this article. If you require more detailed instructions on setting up the CLI, refer to the official guide, where you’ll find comprehensive instructions for CLI setup.

Initializing the Project with Amplify

For this project, I’m using React. To streamline the process of making changes, we’ll configure Amplify so that we can simply run Amplify commands whenever necessary. Follow the steps outlined in the code snippet below. When setting up Amplify with your project, the Amplify CLI will prompt you with questions, and you’ll need to provide appropriate answers. I’ll list all the questions and their corresponding answers to simplify the setup process for your project.

amplify init
# You should run the above command from the root of your project
# After running the above command, it will automatically detech your project and initialized all the default settings accordingly.
# You don't need to change anything but its upto you. I'll share the options I've configured

Name: frontend
Environment: dev
Default editor: Visual Studio Code
App type: javascript
JavaScript framework: react
Source Directory Path: src
Distribution Directory Path: build
Build Command: npm run-script build
Start Command: npm run-script start

Using default provider awscloudformation

# You need to choose authentication method i.e. AWS profile | AWS Access keys. I'll choose AWS Profile

By following the steps above, you’ve successfully initialized the Amplify Project in your application, which in my case is a React app.

Add Authentication with AWS Amplify CLI

Now that you’ve completed the initialization of Amplify, it’s time to create AWS resources using the Amplify CLI that we’ve already set up. Below are the questions that the Amplify CLI will prompt you with, along with their corresponding answers. Simply follow these instructions, and you’ll be ready to proceed.

amplify add auth

# Multiple Options - Choose Manual configuration
Do you want to use the default authentication and security configuration? Manual configuration

# Multiple Options - Choose User Sign-Up, Sign-In, connected ...
Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Stora
ge features for images or other content, Analytics, and more)

# Choose any name or press enter it will automatically created a name for you
Provide a friendly name for your resource that will be used to label this category in the project: frontend5d882adf5d882adf

# Choose any name or press enter it will automatically created a name for you
Enter a name for your identity pool. frontend5d882adf_identitypool_5d882adf

# Multiple Options - Choose No
Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) No

# Multiple Options - Choose No
Do you want to enable 3rd party authentication providers in your identity pool? No

# Choose any name or press enter it will automatically created a name for you
Provide a name for your user pool: frontend5d882adf_userpool_5d882adf

# Multiple Options - Choose 'Username'
How do you want users to be able to sign in? Username

# Multiple Options - Choose 'No'
Do you want to add User Pool Groups? No

# Multiple Options - Choose 'No'
Do you want to add an admin queries API? No

# Multiple Options - Choose 'OFF'
Multifactor authentication (MFA) user login options: OFF

# Multiple Options - Choose 'Disabled ...'
Email based user registration/forgot password: Disabled (Uses SMS/TOTP as an alternative)

# Simply press enter
Please specify an SMS verification message: Your verification code is {####}

Do you want to override the default password policy for this User Pool? No

# First you need to deselect all the existing attributes and then select Phone Number
What attributes are required for signing up? Phone Number (This attribute is not supported by Facebook, Login With Amazon, Sign in with Apple.)

Specify the app's refresh token expiration period (in days): 30

Do you want to specify the user attributes this app can read and write? Yes

# First deselct all the existing attributes and then select Phone Number
Specify read attributes: Phone Number

# Deselect all the existing attributes and press enter - Don't need to select Phone Number it will by default have write permissions when you select read option above
Specify write attributes:

# Multiple Options - Choose 'Custom Auth Challenge ...'
Do you want to enable any of the following capabilities? Custom Auth Challenge Flow (basic scaffolding - not for production)

# Multiple Options - Choose 'No'
Do you want to use an OAuth flow? No

# Multiple Options - Choose 'Yes'
Do you want to configure Lambda Triggers for Cognito? Yes

# Multiple Options - You need to select these options - Cognito Create Auth Challenge, Define Auth Challenge, Pre Sign-up, Verify Auth Challenge Response
Which triggers do you want to enable for Cognito Create Auth Challenge, Define Auth Challenge, Pre Sign-up, Verify Auth Challenge Response

# Multiple Options - Choose 'Create Auth Challenge ...'
What functionality do you want to use for Create Auth Challenge Custom Auth Challenge Scaffolding (Creation)

# Multiple Options - Choose 'Define Auth Challenge Custom ...'
What functionality do you want to use for Define Auth Challenge Custom Auth Challenge Scaffolding (Definition)

# Multiple Options - Choose 'Pre Sign-up Create ...'
What functionality do you want to use for Pre Sign-up Create your own module

# Multiple Options - Choose 'Verify Auth Challenge Response ...'
What functionality do you want to use for Verify Auth Challenge Response Custom Auth Challenge Scaffolding (Verification)

# Then CLI will ask you to update the custom lambda function code. All the code will be provided to you below in the respective sections.
# Simply copy paste the code in the respective file

When prompted by the CLI for the lambda function code, refer to the relevant sections in this blog post. Copy the lambda function code provided and paste it into the corresponding files as instructed.

Create Auth Challenge Lambda Function

Review the code, and you’ll notice that it generates a secret login code and sends it to the user via email. The user is allowed three attempts to enter the correct code before needing to be sent a new login code.

// title boilerplate-create-challenge.js
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

exports.handler = async (event) => {
  //Create a random number for otp
  let secretLoginCode = Math.random().toString(10).substr(2, 6);
  const phoneNumber = event.request.userAttributes.phone_number;

  if (!event.request.session || !event.request.session.length) {
    await sendOTP(secretLoginCode, phoneNumber);
  } else {
    const previousChallenge = event.request.session.slice(-1)[0];
    secretLoginCode = previousChallenge.challengeMetadata.match(/CODE-(\d*)/)[1];
  }

  event.response.publicChallengeParameters = {
    phone_number: event.request.userAttributes.phone_number,
  };

  event.response.privateChallengeParameters = { secretLoginCode };
  event.response.challengeMetadata = `CODE-${secretLoginCode}`;

  return event;
};

async function sendOTP(secretLoginCode, phoneNumber) {
  const sns = new SNSClient({ region: "us-east-1" });
  const publishCommand = new PublishCommand({
    Message: `Your verification code is ${secretLoginCode}`,
    PhoneNumber: phoneNumber,
    MessageStructure: "string",
    MessageAttributes: {
      "AWS.SNS.SMS.SenderID": {
        DataType: "String",
        StringValue: "AppName",
      },
      "AWS.SNS.SMS.SMSType": {
        DataType: "String",
        StringValue: "Transactional",
      },
    },
  });

  return sns.send(publishCommand);
}
// title package.json
{
  ...,
  "dependencies": {
    ...,
    // focus(1:1)
    "@aws-sdk/client-sns": "^3.529.1",
  }
}
// title Cloudformation-template.json
{
  ...,
  "Resources": {
    ...,
    "lambdaexecutionpolicy": {
      ...,
      "Properties": {
        ...,
        "PolicyDocument": {
          ...,
          "Statement": [
            ...,
            // focus(1:6)
            { 
              "Sid": "VisualEditor1", 
              "Effect": "Allow", 
              "Action", "sns:Publish", 
              "Resource": "*"
            }
          ]
        }
      }
    }
  },
  ...
}

To send SMS messages, you’ll need to add SNS permissions. Currently, I’m using a wildcard (*) to grant permission to all SNS resources, but you can limit it as needed. Additionally, make sure to install the @aws-sdk/client-sns package, as it's used in the boilerplate-create-challenge.js file.

Define Auth Challenge Trigger

This function acts as the decision-maker for managing the authentication flow. The event.request.session array contains the entire state of the authentication flow.

If it’s empty, it means the custom authentication flow has just started. If it contains items, it indicates that the custom authentication flow is underway: a challenge was presented to the user, and the user provided an answer which was then verified to be correct or incorrect. In either case, the Define Auth Challenge function must determine the next course of action.

// boilerplate-define-challenge.js

exports.handler = (event) => {
  if (
    event.request.session &&
    event.request.session.find((attempt) => attempt.challengeName !== "CUSTOM_CHALLENGE")
  ) {
    // We only accept custom challenges; fail auth
    event.response.issueTokens = false;
    event.response.failAuthentication = true;
  } else if (
    event.request.session &&
    event.request.session.length >= 3 &&
    event.request.session.slice(-1)[0].challengeResult === false
  ) {
    // The user provided a wrong answer 3 times; fail auth
    event.response.issueTokens = false;
    event.response.failAuthentication = true;
  } else if (
    event.request.session &&
    event.request.session.length &&
    event.request.session.slice(-1)[0].challengeName === "CUSTOM_CHALLENGE" && // Doubly stitched, holds better
    event.request.session.slice(-1)[0].challengeResult === true
  ) {
    // The user provided the right answer; succeed auth
    event.response.issueTokens = true;
    event.response.failAuthentication = false;
  } else {
    // The user did not provide a correct answer yet; present challenge
    event.response.issueTokens = false;
    event.response.failAuthentication = false;
    event.response.challengeName = "CUSTOM_CHALLENGE";
  }

  return event;
};

Verify Auth Challenge Trigger

The sole purpose of this function is to validate whether the user’s answer matches the secretLoginCode.

// boilerplate-verify.js

exports.handler = (event) => {
  if (event.request.privateChallengeParameters.secretLoginCode === event.request.challengeAnswer) {
    event.response.answerCorrect = true;
  } else {
    event.response.answerCorrect = false;
  }

  return event;
};

Pre Signup Trigger

This function automatically confirms users and their email addresses during the sign-up process.

// custom.js

exports.handler = (event) => {
  event.response.autoConfirmUser = true;
  event.response.autoVerifyPhone = true;

  return event;
};

Push Resources to AWS

That’s all there is to it! Now that everything is set up correctly, the final step is to push those resources to AWS by running the following command:

amplify push

No need to manually update resources in the AWS Console whenever you make changes. With everything set up, simply run the Amplify CLI command, and it will handle the rest. Under the hood, Amplify CLI utilizes CloudFormation templates. You can also verify this by navigating to the AWS CloudFormation page in the Console, where you’ll find the CloudFormation template.

Timeout of 3 minutes

Please note that once the custom challenge is presented, the user has a 3-minute window to retrieve the secret login code from their email and submit it as the answer. After this time elapses, the custom authentication flow will time out, and the user will need to initiate a new custom authentication flow to obtain a new secret login code. This 3-minute timeout is enforced server-side by Amazon Cognito and mirrors the timeout period for code entry with multi-factor authentication (MFA).

Conclusion

In conclusion, this comprehensive guide has equipped you with the knowledge and tools to implement a robust passwordless authentication system using AWS Cognito and Amplify. By following the step-by-step instructions for setting up AWS resources and implementing authentication, you’ve gained valuable insights into streamlining the login process for your applications. With these powerful technologies at your disposal, you can enhance security and user experience while simplifying the authentication journey for your users. Embrace the future of authentication with confidence, and unlock new possibilities for your projects.