

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon Cognito と AWS Amplify UI を使用して、React アプリケーションの既存ユーザーを認証する
<a name="authenticate-react-app-users-cognito-amplify-ui"></a>

*Amazon Web Services、Daniel Kozhemyako*

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

このパターンでは、 AWS Amplify UI ライブラリと Amazon Cognito ユーザープールを使用して、既存のフロントエンドの React アプリケーションに認証機能を追加する方法を紹介します。

このパターンは、Amazon Cognito を使用して、アプリケーションの認証、認可、ユーザー管理機能を提供します。また、 の機能をユーザーインターフェイス ([UI) 開発に拡張するオープンソースライブラリである Amplify](https://ui.docs.amplify.aws/react/getting-started/introduction) UI のコンポーネントも使用します。 AWS Amplify [Authenticator UI](https://ui.docs.amplify.aws/react/connected-components/authenticator/advanced) のコンポーネントは、ログインセッションを管理し、Amazon Cognito でユーザーを認証するクラウド接続のワークフローを実行します。

このパターンを実装すると、ユーザーは次の認証情報のいずれかを使用してサインインできます。
+ ユーザー名とパスワード
+ Apple、Facebook、Google、Amazon などのソーシャル ID プロバイダー
+ SAML 2.0 互換または OpenID Connect (OIDC) 互換のエンタープライズ ID プロバイダー

**注記**  
カスタムの認証 UI コンポーネントを作成するには、Authenticator UI コンポーネントをヘッドレスモードで実行します。

## 前提条件と制限
<a name="authenticate-react-app-users-cognito-amplify-ui-prereqs"></a>

**前提条件**
+ アクティブな AWS アカウント
+ React 18.2.0 以降のウェブアプリケーション
+ 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 以降 (Gen 1)
+ Amplify 6.0.16 以降 (Gen 1)

## アーキテクチャ
<a name="authenticate-react-app-users-cognito-amplify-ui-architecture"></a>

**ターゲットアーキテクチャ**

以下の図は、Amazon Cognito を使用して React ウェブアプリケーションのユーザーを認証するアーキテクチャを示しています。

![\[Amazon Cognito が React ウェブアプリケーションのユーザーを認証する。\]](http://docs.aws.amazon.com/ja_jp/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) は、ウェブおよびモバイルアプリの認証、認可、およびユーザー管理機能を提供します。

**その他のツール**
+ [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>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| ユーザープールの作成 | [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>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| 依存関係をインストールします。 | `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/ja_jp/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/ja_jp/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | アプリ開発者 | 
| Authenticator 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 ファイル (コンポーネントの事前ビルド済みテーマを使用するときに必要) をインポートします。`Authenticator` UI コンポーネントは 2 つの戻り値を提供します。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)次のコンポーネント例を参照してください。<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)セクションを参照してください。 | アプリ開発者 | 
| (オプション) セッション情報を取得します。 | ユーザーが認証されると、AAmplify クライアントからセッションに関するデータを取得できます。たとえば、ユーザーのセッションから JSON Web トークン (JWT) を取得して、そのユーザーのセッションからバックエンド API への要求を認証できます。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/ja_jp/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 
| v5 から v6 にアップグレードしたら認証コンポーネント動作しなくなりました。 | `Auth` カテゴリは Amplify v6 の機能アプローチと名前付きパラメータに移行しました。今後は、機能 API は `aws-amplify/auth` パスから直接インポートする必要があります。詳細については、Amplify ドキュメントの「[Migrate from v5 to 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 library](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;
```