

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

# 使用 AWS Amplify 建立 React 應用程式，並使用 Amazon Cognito 新增身分驗證
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito"></a>

*Rishi Singla，Amazon Web Services*

## 摘要
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-summary"></a>

此模式示範如何使用 AWS Amplify 建立以 React 為基礎的應用程式，以及如何使用 Amazon Cognito 將身分驗證新增至前端。AWS Amplify 包含一組工具 （開放原始碼架構、視覺化開發環境、主控台） 和服務 (Web 應用程式和靜態網站託管），以加速 AWS 上的行動和 Web 應用程式開發。

## 先決條件和限制
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-prereqs"></a>

**先決條件 **
+ 作用中的 AWS 帳戶
+ 安裝在機器上的 [Node.js](https://nodejs.org/en/download/) 和 [npm](https://www.npmjs.com/get-npm) 

**產品版本**
+ Node.js 10.x 版或更新版本 （若要驗證您的版本，`node -v`請在終端機視窗中執行）
+ npm 6.x 版或更新版本 （若要驗證您的版本，`npm -v`請在終端機視窗中執行）

## Architecture
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-architecture"></a>

**目標技術堆疊 **
+ AWS Amplify
+ Amazon Cognito

## 工具
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-tools"></a>
+ [Amplify 命令列界面 (CLI)](https://docs.amplify.aws/cli/)
+ [Amplify 程式庫 ](https://docs.amplify.aws/lib/q/platform/react-native/)（開放原始碼用戶端程式庫）
+ [Amplify Studio](https://docs.amplify.aws/console/) （視覺化界面）

## 史詩
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-epics"></a>

### 安裝 AWS Amplify CLI
<a name="install-aws-amplify-cli"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝 Amplify CLI。 | Amplify CLI 是為 React 應用程式建立 AWS 雲端服務的統一工具鏈。若要安裝 Amplify CLI，請執行：<pre>npm install -g @aws-amplify/cli</pre><br />npm 會在有新的主要版本可用時通知您。若是如此，請使用下列命令來升級您的 npm 版本：<pre>npm install -g npm@9.8.0</pre><br />其中 9.8.0 是指您要安裝的版本。 | 應用程式開發人員 | 

### 建立 React 應用程式
<a name="create-a-react-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 React 應用程式。 | 若要建立新的 React 應用程式，請使用 命令：<pre>npx create-react-app amplify-react-application</pre><br />其中 `ampify-react-application`是應用程式的名稱。<br />成功建立應用程式後，您會看到訊息：<pre>Success! Created amplify-react-application</pre><br />系統會為 React 應用程式建立具有各種子資料夾的目錄。 | 應用程式開發人員 | 
| 在本機電腦上啟動應用程式。 | 移至上一個步驟中建立`amplify-react-application`的目錄，然後執行 命令：<pre>amplify-react-application% npm start</pre><br />這會在您的本機電腦上啟動 React 應用程式。 | 應用程式開發人員 | 

### 設定 Amplify CLI
<a name="configure-the-amplify-cli"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Amplify 以連線至您的 AWS 帳戶。 | 執行 命令來設定 Amplify：<pre>amplify-react-application % amplify configure</pre><br />Amplify CLI 會要求您遵循以下步驟來設定對 AWS 帳戶的存取：1. 登入您的 AWS 管理員帳戶。<br />2. 指定您要使用的 AWS 區域。<br />3. 建立具有程式設計存取權的 AWS Identity and Access Management (IAM) 使用者，並將`AdministratorAccess-Amplify`許可政策連接至使用者。<br />4. 建立並複製存取金鑰 ID 和私密存取金鑰。<br />5. 在終端機中輸入這些詳細資訊。<br />6. 建立設定檔名稱或使用預設設定檔。此案例需要具有程式設計存取和長期登入資料的 IAM 使用者，這會造成安全風險。為了協助降低此風險，建議您只為這些使用者提供執行任務所需的許可，並在不再需要這些使用者時將其移除。必要時可以更新存取金鑰。如需詳細資訊，請參閱《*IAM 使用者指南*》中的[更新存取金鑰](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_RotateAccessKey)。<br />這些步驟會顯示在終端機中，如下所示。<pre>Follow these steps to set up access to your AWS account:<br />Sign in to your AWS administrator account:<br />https://console.aws.amazon.com/<br />Press Enter to continue<br />Specify the AWS Region<br />? region:  us-east-1<br />Follow the instructions at<br />https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli<br />to complete the user creation in the AWS console<br />https://console.aws.amazon.com/iamv2/home#/users/create<br />Press Enter to continue<br />Enter the access key of the newly created user:<br />? accessKeyId:  ********************<br />? secretAccessKey:  ****************************************<br />This would update/create the AWS Profile in your local machine<br />? Profile Name:  new<br /><br />Successfully set up the new user.</pre><br />如需這些步驟的詳細資訊，請參閱 Amplify 開發中心中的 [文件](https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli)。 | General AWS，應用程式開發人員 | 

### 初始化 Amplify
<a name="initialize-amplify"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 初始化 Amplify。 | 1. 若要在新目錄中初始化 Amplify，請執行：<pre>amplify init</pre><br />Amplify 會提示您輸入專案名稱和組態參數<br />2. 指定所有參數，然後按 **Y** 以指定組態初始化專案。<pre>Project information<br />| Name: amplifyreactproject<br /><br />| Environment: dev<br /><br />| Default editor: Visual Studio Code<br /><br />| App type: javascript<br /><br />| Javascript framework: react<br /><br />| Source Directory Path: src<br /><br />| Distribution Directory Path: build<br /><br />| Build Command: npm run-script build<br /><br />| Start Command: npm run-script start</pre><br />3. 選取您在上一個步驟中建立的設定檔。資源將部署到您建立的 Amplify 專案中的`dev`環境中。<br />4. 若要確認資源已建立，您可以開啟 [AWS Amplify 主控台](https://console.aws.amazon.com/amplify/home)，並檢視用來建立資源和詳細資訊的 AWS CloudFormation 範本。<pre>Deploying root stack amplifyreactproject [ ====================-------------------- ] 2/4<br />amplify-amplifyreactproject-d… AWS::CloudFormation::Stack     CREATE_IN_PROGRESS            <br /><br />UnauthRole                     AWS::IAM::Role                 CREATE_COMPLETE                 <br /><br />DeploymentBucket               AWS::S3::Bucket                CREATE_IN_PROGRESS         <br /><br />AuthRole                       AWS::IAM::Role                 CREATE_COMPLETE   </pre> | 應用程式開發人員，一般 AWS | 

### 將身分驗證新增至前端
<a name="add-authentication-to-the-frontend"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 新增身分驗證。 | 您可以使用 `amplify add <category>`命令來新增功能，例如使用者登入或後端 API。在此步驟中，您將使用 命令來新增身分驗證。<br />Amplify 提供後端身分驗證服務，其中包含 Amazon Cognito、前端程式庫和插入式 Authenticator UI 元件。功能包括使用者註冊、使用者登入、多重驗證、使用者登出和無密碼登入。您也可以透過與 Amazon、Google 和 Facebook 等聯合身分提供者整合來驗證使用者。Amplify 身分驗證類別與其他 Amplify 類別無縫整合，例如 API、分析和儲存，因此您可以為已驗證和未驗證的使用者定義授權規則。1. 若要設定 React 應用程式的身分驗證，請執行 命令：<pre>amplify-react-application1 % amplify add auth</pre><br />這會顯示下列資訊和提示。您可以根據您的業務和安全需求選擇適當的組態。<pre>Using service: Cognito, provided by: awscloudformation<br /> The current configured provider is Amazon Cognito. <br />Do you want to use the default authentication and security configuration? (Use arrow keys)<br /><br />❯ Default configuration <br /><br />  Default configuration with Social Provider (Federation) <br /><br />  Manual configuration <br /><br />  I want to learn more. </pre><br />2. 如需簡單範例，請選擇預設組態，然後選取使用者的登入機制 （在此情況下為電子郵件）：<pre>How do you want users to be able to sign in? <br /> Username <br /><br />❯ Email <br /><br />  Phone Number <br /><br />  Email or Phone Number <br /><br />  I want to learn more. </pre><br />3. 略過進階設定以完成新增身分驗證資源：  <pre>Do you want to configure advanced settings? (Use arrow keys)<br />❯ No, I am done. <br /><br />  Yes, I want to make some additional changes.</pre><br />4. 建置您的本機後端資源，並在雲端中佈建它們：<pre>amplify-react-application1 % amplify push</pre><br />此命令會對您帳戶中的 Congito 使用者集區進行適當的變更。<br />5. 按 **Y** 以使用 CloudFormation 設定`auth`資源。<br />這會設定下列資源：<pre>UserPool                       AWS::Cognito::UserPool         CREATE_COMPLETE  <br />UserPoolClientWeb              AWS::Cognito::UserPoolClient   CREATE_COMPLETE    <br />UserPoolClientWeb              AWS::Cognito::UserPoolClient   CREATE_COMPLETE            <br />UserPoolClientRole             AWS::IAM::Role                 CREATE_COMPLETE                <br />UserPoolClientLambda           AWS::Lambda::Function          CREATE_COMPLETE  <br />UserPoolClientLambdaPolicy     AWS::IAM::Policy               CREATE_COMPLETE                <br />UserPoolClientLogPolicy        AWS::IAM::Policy               CREATE_IN_PROGRESS                </pre><br />您也可以使用 [AWS Cognito 主控台](https://console.aws.amazon.com/cognito/home)來檢視這些資源 （尋找 Cognito 使用者集區和身分集區）。<br />此步驟會使用 Cognito 使用者集區和身分集區組態，更新 React 應用程式`src`資料夾中`aws-exports.js`的檔案。 | 應用程式開發人員，一般 AWS | 

### 變更 App.js 檔案
<a name="change-the-app-js-file"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 變更 App.js 檔案。 | 在 `src`資料夾中，開啟並修訂 `App.js` 檔案。修改後的檔案看起來應該如下所示：<pre>{  App.Js File after modifications:<br />import React from 'react';<br />import logo from './logo.svg';<br />import './App.css';<br />import { Amplify } from 'aws-amplify';<br />import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';<br />import awsconfig from './aws-exports';<br />Amplify.configure(awsconfig);<br />function App({ signOut }) {<br />  return (<br />      <div><br />      <h1>Thankyou for doing verification</h1><br />      <h2>My Content</h2><br />       <button onClick={signOut}>Sign out</button><br />    </div><br />  );<br />}<br />export default withAuthenticator(App);</pre> | 應用程式開發人員 | 
| 匯入 React 套件。 | `App.js` 檔案會匯入兩個 React 套件。使用 命令安裝這些套件：<pre>amplify-react-application1 % npm install --save aws-amplify @aws-amplify/ui-react</pre> | 應用程式開發人員 | 

### 啟動 React 應用程式並檢查身分驗證
<a name="launch-the-react-app-and-check-authentication"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動應用程式。 | 在本機電腦上啟動 React 應用程式：<pre>amplify-react-application1 % npm start</pre> | 應用程式開發人員，一般 AWS | 
| 檢查身分驗證。 | 檢查應用程式是否提示驗證參數。（在我們的範例中，我們已將電子郵件設定為登入方法。)<br />前端 UI 應該會提示您輸入登入憑證，並提供建立 帳戶的選項。<br />您也可以設定 Amplify 建置程序，將後端新增為連續部署工作流程的一部分。不過，此模式不會涵蓋該選項。 | 應用程式開發人員，一般 AWS | 

## 相關資源
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-resources"></a>
+ [入門 ](https://docs.npmjs.com/getting-started)(npm 文件）
+ [建立獨立的 AWS 帳戶](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html) (AWS 帳戶管理文件） 
+ [AWS Amplify 文件](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html)
+ [Amazon Cognito 文件](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html)