

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Amazon Cognito 和 AWS Amplify UI 驗證現有的 React 應用程式使用者
<a name="authenticate-react-app-users-cognito-amplify-ui"></a>

*Daniel Kozhemyako，Amazon Web Services*

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

此模式說明如何使用 AWS Amplify UI 程式庫和 Amazon Cognitouser 集區，將身分驗證功能新增至現有的前端 React 應用程式。

模式使用 Amazon Cognito 為應用程式提供身分驗證、授權和使用者管理。它還使用 [Amplify UI](https://ui.docs.amplify.aws/react/getting-started/introduction) 中的元件，這是將 功能擴展 AWS Amplify 到使用者介面 (UI) 開發的開放原始碼程式庫。[驗證器 UI](https://ui.docs.amplify.aws/react/connected-components/authenticator/advanced) 元件會管理登入工作階段，並執行透過 Amazon Cognito 驗證使用者的雲端連線工作流程。

實作此模式之後，使用者可以使用下列任何登入資料來登入：
+ 使用者名稱和密碼
+ 社交身分提供者，例如 Apple、Facebook、Google 和 Amazon
+ 與 SAML 2.0 相容或 OpenID Connect (OIDC) 相容的企業身分提供者

**注意**  
若要建立自訂身分驗證 UI 元件，您可以在無周邊模式下執行驗證器 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 代）

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

**目標架構**

下圖顯示使用 Amazon Cognito 驗證 React Web 應用程式使用者的架構。

![Amazon Cognito 會驗證 React Web 應用程式的使用者。](http://docs.aws.amazon.com/zh_tw/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) 是一個開放原始碼 UI 程式庫，提供您可以連接到雲端的可自訂元件。
+ [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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立使用者集區。 | [建立 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 使用者集區與 Authenticator UI 元件整合
<a name="integrate-your-cog-user-pool-with-the-authenticator-ui-component"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝依存項目。 | 若要安裝 `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_tw/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_tw/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 />UI `Authenticator` 元件提供兩個傳回值：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 
| 從 v5 升級到 v6 後，驗證元件停止運作。 | `Auth` 類別已移至 Amplify v6 中的功能方法和具名參數。您現在必須直接從 `aws-amplify/auth` 路徑匯入功能 APIs。如需詳細資訊，請參閱 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>
+ [Amazon Cognito 入門](https://aws.amazon.com/cognito/getting-started/) (AWS 網站）
+ [建立新的 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;
```