Voiced by Amazon Polly |
Overview
In my previous blog, we learned how to integrate the registration process of AWS Cognito in react.js. We created a signup component and configured it with User Pool. In this blog, we will learn the user verification process and a detailed guide to logging in to the user in the AWS Cognito user pool from react.js using the ‘amazon-cognito-identity-js’ library.
Customized Cloud Solutions to Drive your Business Success
- Cloud Migration
- Devops
- AIML & IoT
Introduction to 'amazon-cognito-identity-js'
‘amazon-cognito-identity-js’ is the SDK that allows a JavaScript-enabled application to authenticate the users, view user details, delete users, update users and register the users. It also allows password change for authenticated users and forgot password functionality.
Steps to Create a Component
Step 1:
- Modify the Register.js file for a simple UI to verify the user.
- This code snippet is for simple UI of signup and verifying the user page, where we ask OTP to confirm the user.
- On every change event, we store the value in the respective state so we can use it for the login process.
- After the successful signup, one email with a verification code will send to the registered email address.
- Click on the Verify button “verifyAccount” and it will call the confirmRegistration method of the AWS Cognito. And on the success of verifying the account webpage will redirect to ‘/login.’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
import { CognitoUser, CognitoUserAttribute } from 'amazon-cognito-identity-js'; import { useState } from 'react'; import UserPool from '../UserPool'; function Register() { const [username, setUsername] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [verifyProcess, setVerifyProcess] = useState(false); const [OTP, setOTP] = useState(''); const onSubmit = (e) => { e.preventDefault(); const attributeList = []; attributeList.push( new CognitoUserAttribute({ Name: 'email', Value: email, }) ); UserPool.signUp(username, password, attributeList, null, (err, data) => { if (err) { console.log(err); alert("Couldn't sign up"); } else { console.log(data); setVerifyProcess(true); alert('User Added Successfully'); } }); }; const verifyAccount = (e) => { e.preventDefault(); const user = new CognitoUser({ Username: username, Pool: UserPool, }); console.log(user); user.confirmRegistration(OTP, true, (err, data) => { if (err) { console.log(err); alert("Couldn't verify account"); } else { console.log(data); alert('Account verified successfully'); window.location.href = '/login'; } }); }; return ( <div> {verifyProcess == false ? ( <form onSubmit={onSubmit}> UserName: <input type="text" value={username.toLowerCase().trim()} onChange={(e) => setUsername(e.target.value)} /> <br /> Email: <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /> <br /> Password: <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <button type="submit">Register</button> </form> ) : ( <form onSubmit={verifyAccount}> Enter the OTP: <input type="text" value={OTP} onChange={(e) => setOTP(e.target.value)} /> <br /> <button type="submit">Verify</button> </form> )} </div> ); } export default Register; |
Step 2: Create a ‘Login.js’ file in the src/components directory
Step 3: Add the following code to Login.js file
- This code snippet is for the simple UI of the login page. Where we are asking username and password.
- On every change event, we store the value in the respective state so we can use it for the signup process.
- On the click of Submit button, “onSubmit” will call the Login method of the AWS Cognito.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import { AuthenticationDetails, CognitoUser } from 'amazon-cognito-identity-js'; import { useState } from 'react'; import UserPool from '../UserPool'; function Login() { const [username, setUsername] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const onSubmit = (e) => { e.preventDefault(); const user = new CognitoUser({ Username: username, Pool: UserPool, }); const authDetails = new AuthenticationDetails({ Username: username, Password: password, }); user.authenticateUser(authDetails, { onSuccess: (result) => { console.log('login success', result); }, onFailure: (err) => { console.log('login failure', err); }, newPasswordRequired: (data) => { console.log('new password required', data); }, }); }; return ( <div> <form onSubmit={onSubmit}> Email: <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} /> <br /> Password: <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <button type="submit">Login</button> </form> </div> ); } export default Login; |
Step 4: Add route in App.js file
- In this step, we are setting up the routes for the login page.
- We are importing the Login component from the ‘./Components/Login.
- We are setting up the ‘/login as a path and <Login /> component as an element.
- So, whenever the browser hit the http://localhost:3000/login it will render our Login component on the browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { BrowserRouter, Route, Routes } from 'react-router-dom'; import './App.css'; import Login from './Components/Login'; import Register from './Components/Register'; function App() { return ( <BrowserRouter> <Routes> <Route path="/register" element={<Register />} /> <Route path="/login" element={<Login />} /> </Routes> </BrowserRouter> ); } export default App; |
Step 5: Run the application and open http://localhost:3000/register
Step 6: Fill in the details and click on the Register button and check your AWS Cognito
Step 7: Enter the OTP(Received via mail) and click on verify button
Step 8: Enter the username and password on the login page.
Conclusion
In my next blog, we will see how to implement session management in the application and also see how to log out the user from the application.
Get your new hires billable within 1-60 days. Experience our Capability Development Framework today.
- Cloud Training
- Customized Training
- Experiential Learning
About CloudThat
CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.
CloudThat is the first Indian Company to win the prestigious Microsoft Partner 2024 Award and is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 850k+ professionals in 600+ cloud certifications and completed 500+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, Microsoft Gold Partner, AWS Training Partner, AWS Migration Partner, AWS Data and Analytics Partner, AWS DevOps Competency Partner, AWS GenAI Competency Partner, Amazon QuickSight Service Delivery Partner, Amazon EKS Service Delivery Partner, AWS Microsoft Workload Partners, Amazon EC2 Service Delivery Partner, Amazon ECS Service Delivery Partner, AWS Glue Service Delivery Partner, Amazon Redshift Service Delivery Partner, AWS Control Tower Service Delivery Partner, AWS WAF Service Delivery Partner, Amazon CloudFront Service Delivery Partner, Amazon OpenSearch Service Delivery Partner, AWS DMS Service Delivery Partner, AWS Systems Manager Service Delivery Partner, Amazon RDS Service Delivery Partner, AWS CloudFormation Service Delivery Partner, AWS Config, Amazon EMR and many more.
FAQs
1. Can we verify the user using an email link instead of OTP?
ANS: – Yes, we can verify the user using an email link instead of OTP. For this, we need to configure the Cognito user pool. General Settings => Message Customization => Verification Type Change verification type Code to Link.
2. Can we display user information on the page?
ANS: – Yes, we can display the user information on the page. Once the user is logged in, we will get the user information as a JSON object from the AWS Cognito User Pool. by parsing the JSON object, we can display the user information on the page.
WRITTEN BY Mayur Patel
Comments