

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Amazon Cognito 和 AWS Amplify UI 对现有 React 应用程序用户执行身份验证
<a name="authenticate-react-app-users-cognito-amplify-ui"></a>

*Daniel Kozhemyako，Amazon Web Services*

## Summary
<a name="authenticate-react-app-users-cognito-amplify-ui-summary"></a>

此模式展示了如何使用 AWS Amplify UI 库和 Amazon Cognito 用户池向现有的前端 React 应用程序添加身份验证功能。

此模式使用 Amazon Cognito 为应用程序提供身份验证、授权和用户管理。它还使用 A [mplify UI](https://ui.docs.amplify.aws/react/getting-started/introduction) 中的组件，这是一个开源库，可将的功能扩展 AWS Amplify 到用户界面 (UI) 开发。[Authenticator UI](https://ui.docs.amplify.aws/react/connected-components/authenticator/advanced) 组件管理登录会话，并运行通过 Amazon Cognito 对用户进行身份验证的云连接工作流。

实现此模式后，用户可使用以下任何凭证登录：
+ 用户名和密码
+ 社交身份提供商，例如 Apple、Facebook、Google 和 Amazon
+ SAML 2.0 或 OpenID Connect (OIDC) 兼容的企业身份提供程序

**注意**  
为了创建自定义身份验证 UI 组件，可以在无头模式下运行 Authenticator UI 组件。

## 先决条件和限制
<a name="authenticate-react-app-users-cognito-amplify-ui-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ React 18.2.0 或更高版本的 Web 应用程序
+ Node.js 和 npm 6.14.4 或更高版本，[已安装](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)

**限制**
+ 此模式仅适用于 React Web 应用程序。
+ 此模式使用预先构建的 Amplify UI 组件。该解决方案不包括实现自定义 UI 组件所需步骤。

**产品版本**
+ Amplify UI 6.1.3 或更高版本（第 1 代）
+ Amplify 6.0.16 或更高版本（第 1 代）

## 架构
<a name="authenticate-react-app-users-cognito-amplify-ui-architecture"></a>

**目标架构**

下图介绍了一种使用 Amazon Cognito 对 React Web 应用程序的用户进行身份验证的架构。

![Amazon Cognito 对 React 网络应用程序的用户进行身份验证。](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b2cea053-6931-4404-8aa8-c623ce2024ac/images/b7f69f20-a39d-4a78-8605-7dab73c59052.png)


## 工具
<a name="authenticate-react-app-users-cognito-amplify-ui-tools"></a>

**AWS 服务**
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) 为您的 Web 和移动应用程序提供身份验证、授权和用户管理。

**其他工具**
+ [Amplify UI](https://ui.docs.amplify.aws/react/getting-started/introduction) 是开源用户界面库，提供可自定义的组件，您可以将其连接到云端。
+ [Node.js](https://nodejs.org/en/docs/) 是一个事件驱动的 JavaScript 运行时环境，专为构建可扩展的网络应用程序而设计。
+ [npm](https://docs.npmjs.com/about-npm) 是在 Node.js 环境中运行的软件注册表，用于共享或借用软件包以及管理私有软件包的部署。

## 最佳实践
<a name="authenticate-react-app-users-cognito-amplify-ui-best-practices"></a>

如果正在构建新应用程序，我们建议您使用 Amplify Gen 2。

## 操作说明
<a name="authenticate-react-app-users-cognito-amplify-ui-epics"></a>

### 创建 Amazon Cognito 用户池
<a name="create-an-cog-user-pool"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建用户池。 | [创建 Amazon Cognito 用户池](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html)。配置用户池的登录选项和安全要求，以适合您的使用案例。 | 应用程序开发人员 | 
| 添加应用程序客户端。 | [配置用户池应用程序客户端](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html)。您的应用程序需要通过此客户端才能与 Amazon Cognito 用户池进行交互。 | 应用程序开发人员 | 

### 将 Amazon Cognito 用户池与身份验证器用户界面组件集成
<a name="integrate-your-cog-user-pool-with-the-authenticator-ui-component"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装依赖项。 | 要安装 `aws-amplify` 和 `@aws-amplify/ui-react` 软件包，请从应用程序的根目录运行以下命令：<pre>npm i @aws-amplify/ui-react aws-amplify</pre> | 应用程序开发人员 | 
| 配置用户池。 | 根据下面的示例，创建一个 `aws-exports.js` 文件并保存在 `src` 文件夹中。该文件应包含以下信息：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)<pre>// replace the user pool region, id, and app client id details<br />const awsmobile = {<br />    "aws_project_region": "put_your_region_here",<br />    "aws_cognito_region": "put_your_region_here",<br />    "aws_user_pools_id": "put_your_user_pool_id_here",<br />    "aws_user_pools_web_client_id": "put_your_user_pool_app_id_here"<br />}<br /><br />export default awsmobile;</pre> | 应用程序开发人员 | 
| 导入与配置 Amplify 服务。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 应用程序开发人员 | 
| 添加身份验证器 UI 组件。 | 若要显示 `Authenticator` UI 组件，请在应用程序的入口点文件 (`App.js`) 中添加以下代码行：<pre>import { Authenticator } from '@aws-amplify/ui-react';<br />import '@aws-amplify/ui-react/styles.css';</pre>示例代码片段导入 `Authenticator` UI 组件和 Amplify UI styles.css 文件，这是使用该组件的预构建主题时必需的项。<br />该 `Authenticator` UI 组件提供两个返回值：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)<br />请参见以下示例组件：<pre>function App() {<br />    return (<br />        <Authenticator><br />            {({ signOut, user }) => (<br />                <div><br />                    <p>Welcome {user.username}</p><br />                    <button onClick={signOut}>Sign out</button><br />                </div><br />            )}<br />        </Authenticator><br />    );<br />}</pre>对于示例 `App.js` 文件，请参阅此模式的[其他信息](#authenticate-react-app-users-cognito-amplify-ui-additional)部分。 | 应用程序开发人员 | 
| （可选）检索会话信息。 | 用户通过身份验证后，您可从 Amplify 客户端检索有关其会话的数据。例如，您可从用户的会话中检索 JSON Web 令牌 (JWT)，这样您就可以对来自其会话的请求进行身份验证，然后再向后端 API 发送请求。<br />参见以下含 JWT 请求标头示例：<pre>import { fetchAuthSession } from 'aws-amplify/auth';<br />(await fetchAuthSession()).tokens?.idToken?.toString();</pre> | 应用程序开发人员 | 

## 问题排查
<a name="authenticate-react-app-users-cognito-amplify-ui-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 新用户无法注册此应用程序。 | 如下所述，确保您的 Amazon Cognito 用户池已配置为允许用户自行注册以加入用户池。[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 
| 从 v5 升级到 v6 后，身份验证组件停止工作。 | 在 Amplify v6 中，`Auth` 类别已移至功能化方法，并支持命名参数。现在，必须 APIs 直接从`aws-amplify/auth`路径导入函数。有关更多信息，请参阅 Amplify 文档中的[从 v5 迁移到 v6](https://docs.amplify.aws/gen1/react/build-a-backend/auth/auth-migration-guide/)。 | 

## 相关资源
<a name="authenticate-react-app-users-cognito-amplify-ui-resources"></a>
+ [亚马逊 Cognito（AWS 网站）入门](https://aws.amazon.com/cognito/getting-started/)
+ [创建新 React 应用程序](https://reactjs.org/docs/create-a-new-react-app.html)（React 文档）
+ [什么是 Amazon Cognito？](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) （Amazon Cognito 文档）
+ [Amplify UI 库](https://ui.docs.amplify.aws/)（Amplify 文档）

## 附加信息
<a name="authenticate-react-app-users-cognito-amplify-ui-additional"></a>

该 `App.js` 文件应包含以下代码：

```
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;
```