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 also the official AWS (Amazon Web Services) Advanced Consulting Partner and Training partner and Microsoft gold partner, helping people develop knowledge of the cloud and help their businesses aim for higher goals using best-in-industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.
Drop a query if you have any questions regarding AWS Cognito, ReactJS and I will get back to you quickly.
To get started, go through our Consultancy page and Managed Services Package that is CloudThat’s offerings.
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
Click to Comment