Create a React app by using AWS Amplify and add authentication with Amazon Cognito - AWS Prescriptive Guidance

Create a React app by using AWS Amplify and add authentication with Amazon Cognito

Created by Rishi Singla (AWS)

Environment: PoC or pilot

Technologies: Web & mobile apps; Security, identity, compliance

Workload: All other workloads

AWS services: AWS Amplify; Amazon Cognito

Summary

This pattern demonstrates how to use AWS Amplify to create a React-based app and how to add authentication to the frontend by using Amazon Cognito. AWS Amplify consists of a set of tools (open source framework, visual development environment, console) and services (web app and static website hosting) to accelerate the development of mobile and web apps on AWS.

Prerequisites and limitations

Prerequisites

  • An active AWS account

  • Node.js and npm installed on your machine

Product versions

  • Node.js version 10.x or later (to verify your version, run node -v in a terminal window)

  • npm version 6.x or later (to verify your version, run npm -v in a terminal window)

Architecture

Target technology stack

  • AWS Amplify

  • Amazon Cognito

Tools

Epics

TaskDescriptionSkills required

Install the Amplify CLI.

The Amplify CLI is a unified toolchain for creating AWS Cloud services for your React app. To install the Amplify CLI, run:

npm install -g @aws-amplify/cli

npm will notify you if a new major version is available. If so, use the following command to upgrade your version of npm:

npm install -g npm@9.8.0

where 9.8.0 refers to the version you want to install.

App developer
TaskDescriptionSkills required

Create a React app.

To create a new React app, use the command:

npx create-react-app amplify-react-application

where ampify-react-application is the name of the app.

When the app has been created successfully, you will see the message:

Success! Created amplify-react-application

A directory with various subfolders will be created for the React app.

App developer

Launch the app on your local machine.

Go to the directory amplify-react-application that was created in the previous step and run the command:

amplify-react-application% npm start

This launches the React app on your local machine.

App developer
TaskDescriptionSkills required

Configure Amplify to connect to your AWS account.

Configure Amplify by running the command:

amplify-react-application % amplify configure

The Amplify CLI asks you to follow these steps to set up access to your AWS account:

  1. Sign in to your AWS administrator account.

  2. Specify the AWS Region you want to use.

  3. Create an AWS Identity and Access Management (IAM) user with programmatic access, and attach the AdministratorAccess-Amplify permissions policy to the user.

  4. Create and then copy the access key ID and secret access key.

  5. Enter these details in the terminal.

  6. Create a profile name or use the default profile.

Warning: This scenario requires IAM users with programmatic access and long-term credentials, which present a security risk. To help mitigate this risk, we recommend that you provide these users with only the permissions they require to perform the task and that you remove these users when they are no longer needed. Access keys can be updated if necessary. For more information, see Updating access keys in the IAM User Guide.

These steps appear in the terminal as follows.

Follow these steps to set up access to your AWS account: Sign in to your AWS administrator account: https://console.aws.amazon.com/ Press Enter to continue Specify the AWS Region ? region: us-east-1 Follow the instructions at https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli to complete the user creation in the AWS console https://console.aws.amazon.com/iamv2/home#/users/create Press Enter to continue Enter the access key of the newly created user: ? accessKeyId: ******************** ? secretAccessKey: **************************************** This would update/create the AWS Profile in your local machine ? Profile Name: new Successfully set up the new user.

For more information about these steps, see the documentation in the Amplify Dev Center.

General AWS, App developer
TaskDescriptionSkills required

Initialize Amplify.

  1. To initialize Amplify in the new directory, run:

    amplify init

    Amplify prompts you for the project name and configuration parameters

  2. Specify all parameters, and then press Y to initialize the project with the specified configuration.

    Project information | Name: amplifyreactproject | Environment: dev | Default editor: Visual Studio Code | App type: javascript | Javascript framework: react | Source Directory Path: src | Distribution Directory Path: build | Build Command: npm run-script build | Start Command: npm run-script start
  3. Select the profile you created in the previous step. The resources will be deployed into the dev environment in the Amplify project you created.

  4. To confirm that the resources have been created, you can open the AWS Amplify console and view the AWS CloudFormation template that was used to create the resources and the details.

    Deploying root stack amplifyreactproject [ ====================-------------------- ] 2/4 amplify-amplifyreactproject-d… AWS::CloudFormation::Stack CREATE_IN_PROGRESS UnauthRole AWS::IAM::Role CREATE_COMPLETE DeploymentBucket AWS::S3::Bucket CREATE_IN_PROGRESS AuthRole AWS::IAM::Role CREATE_COMPLETE
App developer, General AWS
TaskDescriptionSkills required

Adding authentication.

You can use the amplify add <category> command to add features such as a user login or a backend API. In this step you will use the command to add authentication.

Amplify provides a backend authentication service with Amazon Cognito, frontend libraries, and a drop-in Authenticator UI component. Features include user sign-up, user sign-in, multi-factor authentication, user sign-out, and passwordless sign-in. You can also authenticate users by integrating with federated identity providers such as Amazon, Google, and Facebook. The Amplify authentication category integrates seamlessly with other Amplify categories such as API, analytics, and storage, so you can define authorization rules for authenticated and unauthenticated users.

  1. To configure authentication for your React app, run the command:

    amplify-react-application1 % amplify add auth

    This displays the following information and prompts. You can choose the appropriate configuration depending on your business and security requirements.

    Using service: Cognito, provided by: awscloudformation The current configured provider is Amazon Cognito. Do you want to use the default authentication and security configuration? (Use arrow keys) ❯ Default configuration Default configuration with Social Provider (Federation) Manual configuration I want to learn more.
  2. For a simple example, choose the default configuration and then select the sign-in mechanism for users (in this case, email):

    How do you want users to be able to sign in? Username ❯ Email Phone Number Email or Phone Number I want to learn more.
  3. Bypass the advanced settings to complete adding authentication resources:  

    Do you want to configure advanced settings? (Use arrow keys) ❯ No, I am done. Yes, I want to make some additional changes.
  4. Build your local backend resources and provision them in the cloud:

    amplify-react-application1 % amplify push

    This command makes the appropriate changes to the Congito user pools in your account.

  5. Press Y to configure the auth resource by using CloudFormation.

    This configures the following resources:

    UserPool AWS::Cognito::UserPool CREATE_COMPLETE UserPoolClientWeb AWS::Cognito::UserPoolClient CREATE_COMPLETE UserPoolClientWeb AWS::Cognito::UserPoolClient CREATE_COMPLETE UserPoolClientRole AWS::IAM::Role CREATE_COMPLETE UserPoolClientLambda AWS::Lambda::Function CREATE_COMPLETE UserPoolClientLambdaPolicy AWS::IAM::Policy CREATE_COMPLETE UserPoolClientLogPolicy AWS::IAM::Policy CREATE_IN_PROGRESS

    You can also use the AWS Cognito console to view these resources (look for Cognito user pools and identity pools).

    This step updates the aws-exports.js file in the src folder for your React app with the Cognito user pool and identity pool configurations.

App developer, General AWS
TaskDescriptionSkills required

Change the App.js file.

In the src folder, open and revise the App.js file. The modified file should look like this:

{ App.Js File after modifications: import React from 'react'; import logo from './logo.svg'; import './App.css'; import { Amplify } from 'aws-amplify'; import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react'; import awsconfig from './aws-exports'; Amplify.configure(awsconfig); function App({ signOut }) { return ( <div> <h1>Thankyou for doing verification</h1> <h2>My Content</h2> <button onClick={signOut}>Sign out</button> </div> ); } export default withAuthenticator(App);
App developer

Import React packages.

The App.js file imports two React packages. Install these packages by using the command:

amplify-react-application1 % npm install --save aws-amplify @aws-amplify/ui-react
App developer
TaskDescriptionSkills required

Launch the app.

Launch the React app on your local machine:

amplify-react-application1 % npm start
App developer, General AWS

Check authentication.

Check whether the app prompts for authentication parameters. (In our example, we’ve configured email as the sign-in method.)

The frontend UI should prompt you for sign-in credentials and provide an option to create an account.

You can also configure the Amplify build process to add the backend as part of a continuous deployment workflow. However, this pattern doesn’t cover that option.

App developer, General AWS

Related resources