Bobcares

AWS Cognito OTP Login: Setup and Usage.

by | Aug 20, 2022

 Let us take a closer look into the aws Cognito OTP login. With the support of AWS support services, we can give you a detailed step-by-step guide on how to enable OTP login in AWS Cognito.

AWS Cognito

aws cognito otp login

Amazon Cognito is an AWS service that is scalable to millions of users. And it allows users to quickly and easily add user sign-up, sign-in, and access control to the online and mobile apps. Aws Cognito’s two main components are user pools and identity pools. User pools are user directories that allow web and mobile app users to sign up and sign in. Identity pools provide AWS credentials to users, allowing them to access other AWS services.

To safeguard the identity of users, add multi-factor authentication (MFA) to an AWS Cognito user pool. MFA introduces a second authentication technique that is independent of the user name and password. One-time passwords (OTPs) are a popular MFA option for businesses wishing to increase security using two-factor authentication (2FA). OTPs sent via email and SMS are a popular kind of 2FA that many enterprises utilize due to user convenience, ease of management, and low associated expenses.

AWS Cognito OTP Login

Setting up an AWS Cognito user pool with a custom auth challenge flow involving three Lambda function triggers (plus one to auto-confirm the user’s phone number as username) is necessary.

This solution adheres to the flow described in the preceding documents. To complete a custom authentication sequence, utilize an AWS Cognito user pool and a collection of AWS Lambda functions as triggers. Additionally, use Amazon SNS to send one-time codes to consumers via SMS text messages. The steps given below explain how the lambda functions work and trigger.

  1. The user inputs their phone number on the custom sign-up/sign-in page. And after that, sent to the AWS Cognito user pool.
  2. On the custom sign-up/sign-in page, the user can enter their phone number. It is subsequently routed to the AWS Cognito user pool.
  3. The “Create Auth Challenge” Lambda function calls by the user pool. This Lambda function generates a secret login code and SMS transmits it to the user’s mobile device over Amazon SNS.
  4. The user downloads the secret login code from their phone and enters it into the custom sign-in page Then returned to the user pool. The user pool will execute the “Validate Auth Challenge Response” Lambda function to verify the users’ responses.
  5. The user pool invokes the “Define Auth Challenge” Lambda function to ensure the successful answering of the challenge and that no further necessity for challenges. In its response to the user pool, the function contains “issueTokens: true.” The user pool now considers the user to be authorized and responds to the user with valid JSON Web Tokens (JWTs).

AWS Cognito OTP Login

  1. Firstly launch the Serverless Application Repository.
  2. After that, enter an Application name and UserPoolName and tick the “I acknowledge…” box.
  3. Finally, choose Deploy.

Deploying through the AWS Serverless Application Repository initiates the establishment of an Amazon CloudFormation stack on the account and begins the creation of resources in the current region. These resources include an AWS Cognito user pool, four Lambda functions, and access to those resources. The template code is shown in the CloudFormation Console for the deployed CloudFormation stack.

Test

Test a custom sign-up and sign-in web client given in this Amplify Passwordless SMS Auth repo after the solution has been deployed via the Serverless Repository. Simply clone the repository and follow the steps provided by the client.

AWS Lambda Function (Triggers)

The four triggers listed below are deployed as Node.js v8.10 runtime functions by AWS Cognito user pools to complete a custom auth challenge flow that allowed users to authenticate using their phone numbers. View these associated Lambda functions in the AWS Cognito user pool > Settings > Triggers after deploying this solution via the AWS Serverless Application Repository.

Pre-sign-up

This function auto-confirms a new user by using the phone number they gave during sign-up as their AWS Cognito user pool username.

1 exports.handler = async event = {
2 event.response.autoConfirmUser = true
3 event.response.autoVerifyPhone = true
4 return event
5}

Create Auth Challenge

This function produces a 6-digit secret code (also known as an OTP, or one-time password) and sends it to the user over SMS. Before resetting and issuing a new code, the user has three tries to enter the correct code.

1 const crypto_secure_random_digit = require("crypto-secure-random-digit");
2 const AWS = require("aws-sdk");
3 var sns = new AWS.SNS();
5 // Main handler
6 exports.handler = async (event = {}) = {
7 let secretLoginCode;
8 if (!event.request.session || !event.request.session.length) {
9 var phone Number = event.request.userAttributes.phone_number;
10 secretLoginCode = crypto_secure_random_digit.randomDigits(6).join("");
11 await sendSMSviaSns(phoneNumber, secretLoginCode); // use SNS for sending SMS,
12 }
13 else {
14 const previousChallenge = event.request.session.slice(-1)[0];
15 secretLoginCode = previousChallenge.challengeMetadata.match(/CODE-(\d*)/)[1];
16 }
17 event.response.publicChallengeParameters = { phone: event.request.userAttributes.phone_number }; 18 event.response.challengeMetadata = CODE-${secret LoginCode}";
19 return event;
20 };
21
22 // Send secret code over SMS via Amazon Simple Notification Service (SNS)
23 async function sendSMSviaSNS(phone Number, secretLoginCode) {
24 const params = { "Message": "[YourAppName] Your secret code: " + secretLoginCode, "Phone Number": phone Number };
25 await sns.publish(params).promise();
26 }
27

Define Auth Challenge

This function manages the authentication flow. The whole status of the authentication flow is present in the session array provided to this Lambda function (event.request.session).

If the session details are empty, the custom authentication flow has only recently begun. If it contains items, the custom authentication procedure is in progress. This implies a challenge is given to the user, and the user after submitting an answer confirms whether it is correct or incorrect. This function determines what happens next in either instance.

export.handler - async (event) → {
if (event.request.session &&
event.request.session.find(attempt → attempt.challengeName = 'CUSTOM_CHALLENGE')) {
// Only accept CUSTOM_CHALLENGES; otherwise 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.issue Tokens = false;
event.response. failAuthentication = true;
} else if (event.request.session &&
event.request.session.length &&
event.request.session.slice(-1)[0].challengeName = 'CUSTOM_CHALLENGE' && event.request.session.slice(-1)[0].challengeResult = true) {
// The user provided the right answer; succeed auth event.
response.issue Tokens = true;
event.response. failAuthentication = false;
} else {
// The user did not provide a correct answer yet; present challenge
event.response.issue Tokens = false;
event.response. failAuthentication = false;
event.response.challengeName = 'CUSTOM_CHALLENGE';
return event;
};

Verify Auth Challenge Response

The purpose of this function is to ensure that the user’s response matches the secret login code supplied to the user. This is the final step in setting up the aws Cognito OTP login.

1 exports.handler = async (event) = {
2 const expectedAnswer = event.request.privateChallengeParameters.secretLoginCode;
3 if (event.request.challengeAnswer = expectedAnswer) {
4 event.response, answerCorrect = true;
5 }
6 else {
7 event.response.answerCorrect = false;
8 }
9 return event;
10 };
11

[Need assistance with similar queries? We are here to help]

Conclusion

To conclude, aws Cognito OTP login allows easy user sign-up and authentication for both web and mobile apps. The OTP provides an extra layer of protection to safeguard the user credentials.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

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

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF