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
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.
- The user inputs their phone number on the custom sign-up/sign-in page. And after that, sent to the AWS Cognito user pool.
- 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.
- 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.
- 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.
- 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
- Firstly launch the Serverless Application Repository.
- After that, enter an Application name and UserPoolName and tick the “I acknowledge…” box.
- 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.
var google_conversion_label = "owonCMyG5nEQ0aD71QM";
0 Comments