When we develop a website or mobile app, we have to add authentication to it. Sometimes we need to maintain different types of users and show them a particular part of the website. While using a serverless backend we use Amazon Cognito user pools to log in to our website or mobile application to maintain separate user access. The user pool is a user directory on Amazon Cognito. In this article, we learn how to do authentication using Amplify Framework and Cognito user pools.
To access AWS amplify and Cognito user pool, you need to have an AWS account. If you have already then you are good to go but if not then you can sign up here.
When we create a website traditionally we build and deploy the web applications and we have control over the HTTP requests that are requested to our server. Our application runs on that server and we are responsible for provisioning and managing the resources for it. But there are some issues,
In serverless architecture, we overcome these issues and it helps us achieve
AWS, Azure, or Google Cloud Platform are completely responsible for developing a piece of code by dynamically designating the resources. And the platform only charges for the number of resources used to run the code. The code sent to the cloud provider for execution is in the form of functions. Sometimes called “Functions as a Service ” or “FaaS”. We use AWS Lambda to communicate with AWS cloud services.
The Amplify Command Line Interface (CLI) is a unified toolchain to create, integrate, and manage the AWS cloud services for your app.
First, we need to install the Amplify CLI. To install run the following command,
$ npm install -g @aws-amplify/cli
After a successful installation, we configure CLI by running,
$ amplify configure
This command navigates to the AWS console and asks you to sign in to the AWS console. After signing in amplify CLI asks you to create an IAM user.
Create a user with AdministratorAccess to your account. So that it can provision AWS resources like Cognito, AppSync, etc
To know more about it click here.
Once you have configured AWS Amplify you need to create an act project.For the rest of the blog we will take a React project as an example. If the project is already created then go to the root directory of the project folder through the command prompt, or if not created then create by using the create-react-app command.
In the root directory of your project run the following command,
$ amplify init
This command runs you through the number of steps in which you choose options that are suitable for your project.
Settings for the React project are shown in the following images:
This will deploy your project in AWS amplify. You can see it in the AWS Amplify console.
After that, we add an authentication resource to our project. Run the following command,
$ amplify add auth
Here you can choose manual configuration also and configure it. Here I’ve just selected the default configuration.
Now we deploy these changes to the cloud by running following command,
$ amplify push
Now the all setup part is done. After this, we create the Cognito user pool where our users are stored.
Now let’s create sign up for new users. For that first, we install some libraries,
$ npm install aws-amplify aws-amplify-react --save
Here we use the auths signUp method to sign up a new user. It will create the user in the Cognito user pool.
import React from "react";
import { Button, Label, Input, FormGroup, Row, Col } from "reactstrap";
import PropTypes from "prop-types";
import {
validateEmail,
validateContact,
validateName,
validateConfirmPassword,
passwordValidation,
} from "../../utils/validations"
import { Auth } from 'aws-amplify';
import { toast } from "react-toastify";
import BUTTON_SPINNER from "./assets/images/SpinnerLoader.svg";
class SignUp extends React.PureComponent {
static propTypes = {
isOpen: PropTypes.bool,
toggle: PropTypes.func,
buttonValue: PropTypes.string,
heading: PropTypes.string,
className: PropTypes.string,
type: PropTypes.string,
};
static defaultProps = {
isOpen: false,
buttonValue: "",
heading: "",
className: "",
type: "",
};
constructor(props) {
super(props);
this.state = {
fullname: "",
email: "",
degree: "",
institution: "",
subspeciality: "",
phone: "",
address: "",
phoneError: false,
addressError: false,
emailError: false,
fullnameError: false,
Btndisabled: true,
emailErrorString: "",
fullnameErrorString: "",
phoneErrorString: "",
addressErrorString: "",
showLoader: false,
responseError: false,
responseErrStr: "",
newPassword: "",
confirmPassword: "",
newPasswordError: false,
newPasswordErrorString: "",
confirmPasswordError: false,
confirmPasswordErrorString: "",
};handleInputChange = (event, type) => {
let {
fullname,
email,
phone,
address,
newPassword,
confirmPassword
} = this.state;
let Btndisabled = true;
if (type === "fullname") {
if (
email.length > 2 &&
phone.length > 2 &&
address.length > 2 &&
newPassword.length > 2 &&
confirmPassword.length > 2 &&
event.target.value.length > 2
) {
Btndisabled = false;
}
this.setState({
fullname: event.target.value,
fullnameError: false,
fullnameErrorString: "",
showLoader: false,
Btndisabled,
});
} else if (type === "email") {
if (
fullname.length > 2 &&
phone.length > 2 &&
address.length > 2 &&
newPassword.length > 2 &&
confirmPassword.length > 2 &&
event.target.value.length > 2
) {
Btndisabled = false;
}
this.setState({
email: event.target.value,
emailError: false,
emailErrorString: "",
showLoader: false,
Btndisabled,
});
} else if (type === "phone") {
if (
fullname.length > 2 &&
email.length > 2 &&
address.length > 2 &&
newPassword.length > 2 &&
confirmPassword.length > 2 &&
event.target.value.length > 2
) {
Btndisabled = false;
}
this.setState({
phone: event.target.value,
phoneError: false,
phoneErrorString: "",
showLoader: false,
Btndisabled,
});
} else if (type === "address") {
if (
fullname.length > 2 &&
email.length > 2 &&
phone.length > 2 &&
newPassword.length > 2 &&
confirmPassword.length > 2 &&
event.target.value.length > 2
) {
Btndisabled = false;
}
this.setState({
address: event.target.value,
addressError: false,
addressErrorString: "",
showLoader: false,
Btndisabled,
});
} else if (type === "newpassword") {
if (
fullname.length > 2 &&
email.length > 2 &&
phone.length > 2 &&
address.length > 2 &&
confirmPassword.length > 2 &&
event.target.value.length > 2
) {
Btndisabled = false;
}
this.setState({
newPassword: event.target.value,
newPasswordError: false,
newPasswordErrorString: "",
showLoader: false,
Btndisabled,
});
} else if (type === "confirmpassword") {
if (
fullname.length > 2 &&
email.length > 2 &&
phone.length > 2 &&
address.length > 2 &&
newPassword.length > 2 &&
event.target.value.length > 2
) {
Btndisabled = false;
}
this.setState({
confirmPassword: event.target.value,
confirmPasswordError: false,
confirmPasswordErrorString: "",
showLoader: false,
Btndisabled,
});
}
};
handleSignUp = () => {
let {
fullname,
email,
phone,
newPassword,
confirmPassword,
} = this.state;
if (
phone.length > 2 &&
email.length > 2 &&
fullname.length > 2 &&
newPassword.length > 2 &&
confirmPassword.length > 2
) {
const isValidatedEmail = validateEmail(email);
const isValidatedPhone = validateContact(phone);
const isValidatedName = validateName(fullname);
const isValidNewPassword = passwordValidation(newPassword);
const isValidConfirmPassword = validateConfirmPassword(
newPassword,
confirmPassword
);
if (!isValidatedEmail) {
this.setState({
emailError: true,
emailErrorString: "You have entered an invalid email address.",
});
}
if (!isValidatedPhone) {
this.setState({
phoneError: true,
phoneErrorString: "Please enter the valid phone number.",
});
}
if (!isValidatedName) {
this.setState({
fullnameError: true,
fullnameErrorString: "Please enter valid User name.",
});
}
if (!isValidNewPassword) {
this.setState({
newPasswordError: true,
newPasswordErrorString: "Password must conatin : 8-15 characters,at least 1 number,at least 1 character(e.g. !,$,&),at least 1 uppercase,at least 1 lowercase",
});
}
if (!isValidConfirmPassword && isValidNewPassword) {
this.setState({
confirmPasswordError: true,
confirmPasswordErrorString: "Confirm password should be same as new password.",
});
}
if (
isValidatedEmail &&
isValidatedPhone &&
isValidatedName &&
isValidNewPassword &&
isValidConfirmPassword
) {
this.setState({
showLoader: true,
});
Auth.signUp({
fullname,
newPassword,
attributes: {
email, // optional
phone // optional - E.164 number convention
// other custom attributes
}
})
.then(data => {
console.log(data)
this.props.history.push("/confirm-password", { username: fullname }
)
})
.catch(err => {
console.log(err)
this.setState({
showLoader: false,
});
toast.error(err.message, {
position: toast.POSITION.BOTTOM_RIGHT,
});
});
} else {
this.setState({ Btndisabled: true });
}
};
}
handleKeyPress = (e, type) => {
if (e.key === "Enter") {
if (!this.state.Btndisabled) {
this.handleSignUp();
}
}
};
handleSubmitBtn = () => {
this.handleSignUp();
};
handleCancelBtn = () => {
this.setState({
fullname: "",
email: "",
phone: "",
address: "",
phoneError: false,
addressError: false,
emailError: false,
fullnameError: false,
Btndisabled: true,
emailErrorString: "",
fullnameErrorString: "",
phoneErrorString: "",
addressErrorString: "",
showLoader: false,
responseError: false,
responseErrStr: "",
newPassword: "",
confirmPassword: "",
newPasswordError: false,
newPasswordErrorString: "",
confirmPasswordError: false,
confirmPasswordErrorString: "",
});
};
render() {
let { type } = this.props;
let {
Btndisabled,
fullnameError,
fullnameErrorString,
emailError,
emailErrorString,
showLoader,
phoneError,
phoneErrorString,
responseErrStr,
responseError,
newPassword,
newPasswordError,
newPasswordErrorString,
confirmPassword,
confirmPasswordError,
confirmPasswordErrorString,
} = this.state;
return (
<div className="login-main-div-container">
<Row >
<Col className="login-form-div">
<div className="row">
<FormGroup className="offset-md-4 col-md-6">
<div className="title">{"SignUp"}</div>
<div className="mb-20">{"Enter below details to sign up new user"}</div>
</FormGroup>
<FormGroup className="offset-md-2 col-md-8 mt40 mb40">
{responseError && (
<div className="input-error-style">{responseErrStr}</div>
)}
<Label className="global-label-text">{"Name"}</Label>
<Input
className="page-input-box-style"
autoComplete={"off"}
placeholder={"Name"}
onChange={(e) =>
this.handleInputChange(e, "fullname")
}
maxLength="100"
invalid={fullnameError}
/>
{fullnameError && (
<div className="input-error-style">{fullnameErrorString}</div>
)}
</FormGroup>
<FormGroup className="offset-md-2 col-md-8 offset-1 col-10 mt40 mb40">
<Label className="global-label-text">{"Email"}</Label>
<Input
className="page-input-box-style"
autoComplete={"off"}
placeholder={"Email"}
onChange={(e) => this.handleInputChange(e, "email")}
maxLength="100"
invalid={emailError}
/>
{emailError && (
<div className="input-error-style">{emailErrorString}</div>
)}
</FormGroup>
<FormGroup className="offset-md-2 col-md-8 offset-1 col-10 mt40 mb40">
<Label className="global-label-text">{"Password"}</Label>
<Input
{...this.props}
// handleKeyPress={this.handleKeyPress}
onChange={(e) =>
this.handleInputChange(e, "newpassword")
}
value={newPassword}
className={"page-input-box-style form-control"}
maxLength={"20"}
placeholder={"Password"}
invalid={newPasswordError}
/>
{newPasswordError && (
<div className="input-error-style">{newPasswordErrorString}</div>
)}
</FormGroup>
<FormGroup className="offset-md-2 col-md-8 offset-1 col-10 mt40 mb40">
<Label className="global-label-text">
{"Confirm Password"}
</Label>
<Input
{...this.props}
onKeyPress={(e) => this.handleKeyPress(e)}
onChange={(e) =>
this.handleInputChange(e, "confirmpassword")
}
value={confirmPassword}
className={"page-input-box-style form-control"}
maxLength={"20"}
placeholder={"ConfirmPassword"}
invalid={confirmPasswordError}
/>
{confirmPasswordError && (
<div className="input-error-style">
{confirmPasswordErrorString}
</div>
)}
</FormGroup>
<FormGroup className="offset-md-2 col-md-8 offset-1 col-10 mt40 mb40">
<Label className="global-label-text">
{"Phone"}
</Label>
<Input
className="page-input-box-style"
autoComplete={"off"}
placeholder={"Phone"}
onChange={(e) => this.handleInputChange(e, "phone")}
maxLength="10"
invalid={phoneError}
/>
{phoneError && (
<div className="input-error-style">{phoneErrorString}</div>
)}
</FormGroup>
<FormGroup className="offset-md-2 col-md-8 offset-1 col-10 mt40 mb40">
<div className="inline-flex">
<Button
className="warning-confirm-button"
// disabled={Btndisabled || showLoader}
onClick={() => this.handleSubmitBtn()}
>
{showLoader && <img src={BUTTON_SPINNER} alt="" height="25px" />}{" "}
{"Sign Up"}
</Button>
<div
className="warning-modal-cancel-btn cursor-pointer"
onClick={this.handleCancelBtn}
>
{"Cancel"}
</div>
</div>
</FormGroup>
</div>
</Col>
</Row>
</div>
);
}
}
export default SignUp;
}
After sign up, we will create the user in the Cognito User Pool and send the verification code on the email provided by the user at the time of sign up. So we will create a Confirm Sign Up page where we can validate the code from the user and call Auth’s confirm SignUp method which confirms the user and sets the email verified to true.
Confirm Sign up
import React from "react"; import Plot from "react-plotly.js"; class Graph extends React.Component { constructor(props) { super(props); this.state = { data: [{ values: [19, 26, 55], labels: ['Residential', 'Non-Residential', 'Utility'], type: 'pie' }], layout: { height: 400, width: 500, title: "Pie chart" } }; } render() { return ( <div style={{ width: "100%", height: "100%" }}> <Plot data={this.state.data} layout={this.state.layout} onInitialized={(figure) => this.setState(figure)} onUpdate={(figure) => this.setState(figure)} /> </div> ); } } export default Graph;
For Login, we will use the SignIn method which returns the tokens and user details to us. We store those tokens in our local storage. And redirect to the home page.
import React from "react"; import Plot from "react-plotly.js"; class Graph extends React.Component { constructor(props) { super(props); this.state = { data: [ { x: [1, 2, 3, 4], y: [0, 2, 3, 5], fill: 'tozeroy', type: 'scatter', name: 'Vendor' }, { x: [1, 2, 3, 4], y: [3, 5, 1, 7], fill: 'tonexty', type: 'scatter', name: 'Provider' }], layout: { height: 400, width: 600, title: "Area chart" } }; } render() { return ( <div style={{ width: "100%", height: "100%" }}> <Plot data={this.state.data} layout={this.state.layout} onInitialized={(figure) => this.setState(figure)} onUpdate={(figure) => this.setState(figure)} /> </div> ); } } export default Graph;
Here we did SignUp and SignIn using AWS Amplify and Cognito User Pool. Also, We can create functionalities like Forgot Password, Reset Password using AWS-amplify libraries Auth modules methods.
Hope you like this article where we learn about, how we can add authentication using AWS Amplify and Cognito. If you have any doubts please comments us.
To know more about it please follow below references:
How to Effectively Hire and Manage a Remote Team of Developers.
We had very close go live timeline and MindBowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Our CISO was extremely impressed by Mindbowser’s work. It is pretty rare to see this kind of clean security report so early in the company’s journey. Huge Thank you for the disciplined approach here.
Founder, TrestleIQ
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
The flexibility and capacity of the Mindbower staff has been impressive.
CEO, ProofPilot
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.
Founder, Courtyardly
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork