Authentication using AWS Amplify and Cognito

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.

Prerequisites

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.

What is a serverless architecture?

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,

  • To keep the server up we get charged even when we are not serving any requests
  • We are responsible for server uptime and server maintenance and its resources
  • Also responsible for implementing the proper security updates to the server
  • When our usage scales up or scales down we need to manage to scale up or down our server

In serverless architecture, we overcome these issues and it helps us achieve

  • Low maintenance
  • Low cost
  • Scalability

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.

Check Out What It Takes To Build A Successful App Here

Amplify CLI Setup

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.

App setup

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:

React project
React project
React project
React project

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.

We Build HIPPA Complaint Telehealth Platform Using AWS Cloud

SignUp

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;

Login

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.

coma

Conclusion

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:

Getting Started with Amplify

Amplify Signin and Signout

Amplify password and User management

 

Get a team of Full Stack Developers started within 24 hours

Keep Reading

Keep Reading

Launch Faster with Low Cost: Master GTM with Pre-built Solutions in Our Webinar!

Register Today!
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?