Authenticate existing React application users by using Amazon Cognito and AWS Amplify UI - AWS Prescriptive Guidance

Authenticate existing React application users by using Amazon Cognito and AWS Amplify UI

Created by Daniel Kozhemyako (AWS)

Environment: Production

Technologies: Web & mobile apps; Security, identity, compliance; Business productivity; Analytics

AWS services: Amazon Cognito; AWS Amplify; Amazon Connect; AWS Management Console

Summary

This pattern shows how to add authentication capabilities to an existing frontend React application by using an AWS Amplify UI library and an Amazon Cognito user pool.

The pattern uses Amazon Cognito to provide authentication, authorization, and user management for the application. It also uses a component from Amplify UI, an open-source library that extends the capabilities of AWS Amplify to user interface (UI) development. The Authenticator UI component manages login sessions and runs the cloud-connected workflow that authenticates users through Amazon Cognito.

After you implement this pattern, users can sign in by using any of the following credentials:

  • User name and password

  • Social identity providers, such as Apple, Facebook, Google, and Amazon

  • Enterprise identity providers that are either SAML 2.0 compatible or OpenID Connect (OIDC) compatible

Note: To create a custom authentication UI component, you can run the Authenticator UI component in headless mode.

Prerequisites and limitations

Prerequisites

  • An active AWS account

  • A React 18.2.0 or later web application

  • Node.js and npm 6.14.4 or later, installed

Limitations

  • This pattern applies to React web applications only.

  • This pattern uses a prebuilt Amplify UI component. The solution doesn’t cover the steps required to implement a custom UI component.

Product versions

  • Amplify UI 6.1.3 or later (Gen 1)

  • Amplify 6.0.16 or later (Gen 1)

Architecture

Target architecture

The following diagram shows an architecture that uses Amazon Cognito to authenticate users for a React web application.

Amazon Cognito authenticates users for a React web application.

Tools

AWS services

  • Amazon Cognito provides authentication, authorization, and user management for web and mobile apps.

Other tools

  • Amplify UI is an open-source UI library that provides customizable components that you can connect to the cloud.

  • Node.js is an event-driven JavaScript runtime environment designed for building scalable network applications.

  • npm is a software registry that runs in a Node.js environment and is used to share or borrow packages and manage deployment of private packages.

Best practices

If you're building a new application, we recommend that you use Amplify Gen 2.

Epics

TaskDescriptionSkills required

Create a user pool.

Create an Amazon Cognito user pool. Configure the user pool’s sign-in options and security requirements to fit your use case.

App developer

Add an app client.

Configure a user pool app client. This client is required for your application to interact with the Amazon Cognito user pool.

App developer
TaskDescriptionSkills required

Install dependencies.

To install the aws-amplify and @aws-amplify/ui-react packages, run the following command from your application’s root directory:

npm i @aws-amplify/ui-react aws-amplify
App developer

Configure the user pool.

Based on the following example, create an aws-exports.js file and save in the src folder. The file should include the following information:

  • AWS Region that your Amazon Cognito user pool is in

  • Amazon Cognito user pool ID

  • App client ID

// replace the user pool region, id, and app client id details const awsmobile = { "aws_project_region": "put_your_region_here", "aws_cognito_region": "put_your_region_here", "aws_user_pools_id": "put_your_user_pool_id_here", "aws_user_pools_web_client_id": "put_your_user_pool_app_id_here" } export default awsmobile;
App developer

Import and configure the Amplify service.

  1. In the application’s entry point file (for example, App.js), import and load the aws-exports.js file by entering the following lines of code:

    import { Amplify } from 'aws-amplify'; import awsExports from './aws-exports';
  2. Based on the following example, configure the Amplify client by using the aws-exports.js file:

    // Configure Amplify in index file or root file Amplify.configure({ ...awsExports });

    For more information, see Configure Amplify categories in the Amplify documentation.

App developer

Add the Authenticator UI component.

To display the Authenticator UI component, add the following lines of code to the application’s entry point file (App.js):

import { Authenticator } from '@aws-amplify/ui-react'; import '@aws-amplify/ui-react/styles.css';

Note: The example code snippet imports the Authenticator UI component and the Amplify UI styles.css file, which is required when using the component’s prebuilt themes.

The Authenticator UI component provides two return values:

  • User details

  • A function that can be invoked to sign the user out

See the following example component:

function App() { return ( <Authenticator> {({ signOut, user }) => ( <div> <p>Welcome {user.username}</p> <button onClick={signOut}>Sign out</button> </div> )} </Authenticator> ); }

Note: For an example App.js file, see the Additional information section of this pattern.

App developer

(Optional) Retrieve session information.

After a user is authenticated, you can retrieve data from the Amplify client about their session. For example, you can retrieve the JSON web token (JWT) from a user’s session so that you can authenticate the requests from their session to a backend API.

See the following example of a request header that includes a JWT:

import { fetchAuthSession } from 'aws-amplify/auth'; (await fetchAuthSession()).tokens?.idToken?.toString();
App developer

Troubleshooting

IssueSolution

New users can’t sign up for the application.

As follows, make sure that your Amazon Cognito user pool is configured to allow users to sign themselves up to be in the user pool:

  • Sign in to the AWS Management Console, and then open the Amazon Cognito console.

  • In the left navigation pane, choose User pools.

  • Choose your user pool from the list.

  • Under General Settings, choose Policies.

  • Choose Allow users to sign themselves up.

Auth component stopped working after upgrading from v5 to v6.

The Auth category has moved to a functional approach and named parameters in Amplify v6. You must now import the functional APIs directly from the aws-amplify/auth path. For more information, see Migrate from v5 to v6 in the Amplify documentation.

Related resources

Additional information

The App.js file should contain the following code:

import './App.css'; import { Amplify } from 'aws-amplify'; import awsExports from './aws-exports'; import { fetchAuthSession } from 'aws-amplify/auth'; import { Authenticator } from '@aws-amplify/ui-react'; import '@aws-amplify/ui-react/styles.css'; Amplify.configure({ ...awsExports }); let token = (await fetchAuthSession()).tokens?.idToken?.toString(); function App() { return ( <Authenticator> {({ signOut, user }) => ( <div> <p>Welcome {user.username}</p> <p>Your token is: {token}</p> <button onClick={signOut}>Sign out</button> </div> )} </Authenticator> ); } export default App;