ソーシャルプロバイダーのサインインを追加
アプリにソーシャルプロバイダー(Apple、Amazon、Facebook、Google など)の既存アカウントを使用したサインインと認証を有効にできます。バックエンドリソースを設定した後、そのプロバイダーのサインインアプリを設定できます。このプロセスはセキュアに認証情報を交換し、ユーザー情報を収集します。この情報は、アプリで新しいユーザーを作成するか、ソーシャルアカウントを既存ユーザーにリンクするために使用できます。ソーシャルプロバイダーのサインインを組み込むことで、ユーザーに合理化された登録、より多くのサインインオプション、および既存アカウントとアプリ間の統合エクスペリエンスを提供します。
このガイドでは、まずプロバイダーで開発者アカウントをセットアップし、その後、Auth カテゴリを設定し、ソーシャルサインインをアプリに統合する方法を説明します。
開始する前に、以下が必要です:
- Amplify プロジェクト
- インストールして設定された Amplify ライブラリ
詳細を学ぶOAuth 認証の仕組みを確認
ソーシャルプロバイダーのサインインを組み込む推奨される方法は、OAuth リダイレクトを使用することです。これによりユーザーはソーシャルメディアアカウントを使用してサインインでき、Cognito ユーザープールに対応するユーザーが作成されます。
OAuth 2.0 は、Web およびモバイルアプリケーションがユーザー情報(「スコープ」)に限定的にアクセスするために使用する一般的な認可フレームワークです。OAuth で一般的に聞かれるアナロジーは飛行機の搭乗またはホテルの宿泊です。身分証明書の提示は認証部分(アプリへのサインイン)であり、搭乗券/ホテルキーの使用はアクセスを許可されている部分です。
Amplify での OAuth サポートは Cognito ユーザープールを使用し、ソーシャルプロバイダーでのフェデレーションをサポートしており、ユーザーがサインイン後、ユーザープールに対応するユーザーが自動的に作成されます。この設計では、アプリにソーシャルプロバイダーの SDK を含める必要はありません。これらのソーシャルプロバイダーで開発者アカウントをセットアップした後、amplify add auth を実行し、ソーシャルプロバイダーオプションを選択することで、Auth カテゴリを設定できます。その後、アプリで signInWithRedirect() を使用して、事前構築された「ホストされた UI」を表示するか、プロバイダー名を渡す(例:signInWithRedirect({provider:'Facebook'}))ことで、直接インターフェースし、独自の UI を構築できます。
ソーシャル認証プロバイダーをセットアップ
Amplify Auth でソーシャルサインインを設定する前に、使用している各プロバイダーで開発者アカウントをセットアップする必要があります。
-
Facebook の認証情報でサインインします。
-
トップナビゲーションバーから My Apps を選択し、ロードされたページで Create App を選択します。
-
ユースケースについて、Set up Facebook Login を選択します。
-
プラットフォームについて、Website を選択し、No, I'm not building a game を選択します。
-
Facebook アプリに名前を付け、Create app を選択します。
-
左のナビゲーションバーで、Settings を選択してから Basic を選択します。
-
App ID と App Secret をメモしておきます。次のセクションの CLI フローで使用します。
-
Google 開発者コンソールに移動します。
-
Select a project をクリックします。
-
NEW PROJECT をクリックします。
-
プロジェクト名を入力して CREATE をクリックします。
-
プロジェクトが作成されたら、左のナビゲーションメニューから APIs & Services を選択し、次に Credentials を選択します。
-
CONFIGURE CONSENT SCREEN をクリックします。
-
CREATE をクリックします。
-
App Information と Developer contact information を入力します。これらは必須フィールドであり、3 回(OAuth 同意画面 -> スコープ -> テストユーザー)SAVE AND CONTINUE をクリックして、同意画面のセットアップを完了します。
-
Credentials タブに戻り、Create credentials ドロップダウンリストから OAuth client ID を選択して OAuth2.0 認証情報を作成します。
-
Application type として Web application を選択し、OAuth クライアントに名前を付けます。
-
Create をクリックします。
-
Your client ID と Your Client Secret をメモしておきます。次のセクションの CLI フローで必要です。
-
OK を選択します。
-
Amazon の認証情報でサインインします。
-
Amazon クライアント ID とクライアントシークレットを受け取るために、Amazon セキュリティプロファイルを作成する必要があります。Create a Security Profile を選択します。
-
Security Profile Name、Security Profile Description、および Consent Privacy Notice URL を入力します。
-
Save を選択します。
-
Show Client ID と Client Secret を選択してクライアント ID とシークレットを表示します。次のセクションの CLI フローで必要です。
-
Apple 開発者認証情報でサインインします。
-
メイン開発者ポータルページで、Certificates, IDs, & Profiles を選択します。
-
左のナビゲーションバーで、Identifier を選択します。
-
Identifiers ページで、plus icon (+) を選択します。
-
Register a New Identifier ページで、App IDs を選択します。
-
Register an App ID ページで、App ID Prefix の下の Team ID 値をメモしておきます。
-
Description テキストボックスに説明を入力し、iOS アプリの
bundleIDを入力します。 -
Capabilities の下で、Sign in with Apple を選択します。
-
Continue を選択し、設定を確認してから Register を選択します。
-
Identifiers ページで、右側で App IDs を選択してから Services ID を選択します。
-
plus icon (+) を選択し、Register a New Identifier ページで Services IDs を選択します。
-
Description テキストボックスに説明を入力し、Service ID の識別子を入力します。
-
Continue を選択して Service ID を登録します。
ソーシャルプロバイダーでの開発者アカウントのセットアップが完了し、Amplify プロジェクトに戻って次のステップに進むことができます。
Auth カテゴリを設定
ソーシャルプロバイダーを設定したら、Amplify CLI を通じて Auth 設定を更新できます。
CLI を開始するには、プロジェクトのルートフォルダで以下を実行します:
amplify add auth ## すでに設定されている場合は「amplify update auth」次のオプションを選択します:
? Do you want to use the default authentication and security configuration? `Default configuration with Social Provider (Federation)`? How do you want users to be able to sign in? `Username`? Do you want to configure advanced settings? `No, I am done.`? What domain name prefix you want us to create for you? `(default)`? Enter your redirect signin URI: `http://localhost:3000/`? Do you want to add another redirect signin URI `No`? Enter your redirect signout URI: `http://localhost:3000/`? Do you want to add another redirect signout URI `No`? Select the social providers you want to configure for your user pool: `<適切なトークンを入力するようにプロバイダーを選択して、プロンプトに従います>`次に、amplify push を実行して変更を公開します。完了すると、Web UI の自動生成 URL が表示されます。CLI で amplify status を実行することにより、いつでもユーザープールドメイン URL を取得できます。
ここで、このURL をソーシャルプロバイダーに知らせる必要があります:
-
Facebook の認証情報で Facebook 開発者アカウントに サインインします。
-
トップナビゲーションバーから My Apps を選択し、Apps ページで、前に作成したアプリを選択します。
-
左のナビゲーションバーで、Products を選択します。Facebook Login が追加されていない場合は追加します。
-
すでに追加されている場合は、Configure ドロップダウンの下の Settings を選択します。
-
Valid OAuth Redirect URIs の下に、
/oauth2/idpresponseエンドポイント付きのユーザープールドメインを入力します。https://<your-user-pool-domain>/oauth2/idpresponse
- 変更を保存します。
-
Google 開発者コンソールに移動します。
-
左のナビゲーションバーで、Pinned の下の APIs and Services、またはピン留めされていない場合は More Products の下を探します。
-
APIs and Services サブメニュー内で、Credentials を選択します。
-
最初のステップで作成したクライアントを選択し、Edit ボタンをクリックします。
-
Authorized Javascript origins フォームにユーザープールドメインを入力します。
-
Authorized Redirect URIs に、
/oauth2/idpresponseエンドポイント付きのユーザープールドメインを入力します。注: エンドポイントを追加するときにエラーメッセージ
Invalid Redirect: domain must be added to the authorized domains list before submitting.が表示された場合は、Authorized Domains List に移動してドメインを追加してください。 -
Save をクリックします。
-
Amazon の認証情報でサインインします。
-
ギアアイコンの上にカーソルを移動し、前のステップで作成したセキュリティプロファイルに関連付けられた Web Settings を選択してから、Edit を選択します。
-
ユーザープールドメインを Allowed Origins に入力し、
/oauth2/idpresponseエンドポイント付きのユーザープールドメインを Allowed Return URLs に入力します。 -
Save を選択します。
-
Apple 開発者認証情報でサインインします。
-
メイン開発者ポータルページで、Certificates, IDs, & Profiles を選択します。
-
左のナビゲーションバーで、Identifiers を選択してから、右側のドロップダウンリストから Service IDs を選択します。
-
上記のセクションでセットアップしたときに作成した Service ID を選択します。
-
Sign In with Apple を有効にし、Configure を選択します。
-
Primary App ID の下で、前に作成した App ID を選択します。
-
Domains and Subdomains にユーザープールドメインを入力します。
-
Return URLs に、
/oauth2/idpresponseエンドポイント付きのユーザープールドメインを入力します。 -
Next をクリックし、情報を確認してから Done を選択します。
-
Edit your Services ID Configuration で Continue をクリックし、情報を確認してから Save を選択します。
-
メイン Certificates, Identifiers & Profiles で、Keys を選択します。
-
Keys ページで、plus icon (+) を選択します。
-
Key Name の下にキーの名前を入力します。
-
Sign in with Apple を有効にし、Configure を選択します。
-
Primary App ID の下で、前に作成した App ID を選択します。
-
Save をクリックします。
-
Register a New Key で Continue をクリックし、情報を確認してから Register を選択します。
-
新しいページにリダイレクトされます。Key ID をメモしておき、秘密鍵を含む .p8 ファイルをダウンロードします。
Auth カテゴリを設定し、ソーシャルプロバイダーで URL を更新しました。これでアプリのフロントエンドをセットアップできます。
フロントエンドをセットアップ
OAuth エンドポイント(Cognito ホストされた UI)を設定した後、signInWithRedirect 関数を呼び出すことでアプリを統合できます。これによりユーザーは Cognito ホストされた UI にリダイレクトされ、ユーザー名とパスワードでのサインイン、および設定したソーシャルプロバイダーのいずれでもサインインするオプションが表示されます。また、provider 引数に Amazon、Apple、Facebook、または Google を渡す(例:signInWithRedirect({ provider: 'Amazon' }))と、ホストされた UI をバイパスし、以下の例に示すようにソーシャルプロバイダーと直接フェデレーションできます。
カスタム状態を追加
カスタム状態は必須ではありませんが、追加したい場合は、文字列値を渡す(例:signInWithRedirect({ customState: 'xyz' }))ことで、Hub を介してカスタム状態をリッスンできます。また、Hub イベント処理システムを使用して、signInWithRedirect() を使用エラーをキャッチし、signInWithRedirect_failure イベントをリッスンできます。
import React, { useEffect, useState } from "react";import { Hub } from "aws-amplify/utils";import { signInWithRedirect, signOut, getCurrentUser, AuthUser } from "aws-amplify/auth";
function App() { const [user, setUser] = useState<AuthUser | null>(null); const [error, setError] = useState<unknown>(null); const [customState, setCustomState] = useState<string | null>(null);
useEffect(() => { const unsubscribe = Hub.listen("auth", ({ payload }) => { switch (payload.event) { case "signInWithRedirect": getUser(); break; case "signInWithRedirect_failure": setError("An error has occurred during the OAuth flow."); break; case "customOAuthState": setCustomState(payload.data); // this is the customState provided on signInWithRedirect function break; } });
getUser();
return unsubscribe; }, []);
const getUser = async (): Promise<void> => { try { const currentUser = await getCurrentUser(); setUser(currentUser); } catch (error) { console.error(error); console.log("Not signed in"); } };
return ( <div className="App"> <button onClick={() => signInWithRedirect({ customState: "shopping-cart"})}>Open Hosted UI</button> <button onClick={() => signInWithRedirect({ provider: "Facebook", customState: "shopping-cart" })}> Open Facebook </button> <button onClick={() => signInWithRedirect({ provider: "Google", customState: "shopping-cart" })}> Open Google </button> <button onClick={() => signInWithRedirect({ provider: "Amazon", customState: "shopping-cart" })}> Open Amazon </button> <button onClick={() => signInWithRedirect({ provider: "Apple", customState: "shopping-cart" })}> Open Apple </button> <button onClick={() => signOut()}>Sign Out</button> <div>{user?.username}</div> <div>{customState}</div> </div> );}import React, { useEffect, useState } from "react";import { Hub } from "aws-amplify/utils";import { signInWithRedirect, signOut, getCurrentUser } from "aws-amplify/auth";
function App() { const [user, setUser] = useState(null); const [error, setError] = useState(null); const [customState, setCustomState] = useState(null);
useEffect(() => { const unsubscribe = Hub.listen("auth", ({ payload }) => { switch (payload.event) { case "signInWithRedirect": getUser(); break; case "signInWithRedirect_failure": setError("An error has occurred during the OAuth flow."); break; case "customOAuthState": setCustomState(payload.data); // this is the customState provided on signInWithRedirect function break; } });
getUser();
return unsubscribe; }, []);
const getUser = async () => { try { const currentUser = await getCurrentUser(); setUser(currentUser); } catch (error) { console.error(error); console.log("Not signed in"); } };
return ( <div className="App"> <button onClick={() => signInWithRedirect({ customState: "shopping-cart"})}>Open Hosted UI</button> <button onClick={() => signInWithRedirect({ provider: "Facebook", customState: "shopping-cart" })}> Open Facebook </button> <button onClick={() => signInWithRedirect({ provider: "Google", customState: "shopping-cart" })}> Open Google </button> <button onClick={() => signInWithRedirect({ provider: "Amazon", customState: "shopping-cart" })}> Open Amazon </button> <button onClick={() => signInWithRedirect({ provider: "Apple", customState: "shopping-cart" })}> Open Apple </button> <button onClick={() => signOut()}>Sign Out</button> <div>{user?.username}</div> <div>{customState}</div> </div> );}リダイレクト URL
サインイン & サインアウト リダイレクト URL は、サインインまたはサインアウト操作の実行後にエンドユーザーをリダイレクトするために使用されます。開発(http://localhost:3000/)本番環境(https://www.example.com/)用に異なる URL を指定したり、ユーザーをアプリに戻す前に中間 URL にリダイレクトしたりするなど、複数の URL を指定する場合があります。
例複数のリダイレクト URL を使用した完全な例
import React, { useEffect, useState } from "react";import { Amplify } from "aws-amplify";import { Hub } from "aws-amplify/utils";import { signInWithRedirect, signOut, getCurrentUser } from "aws-amplify/auth";import { AuthUser } from "aws-amplify/auth";
Amplify.configure({ Auth: { Cognito: { loginWith: { oauth: { redirectSignIn: [ "http://localhost:3000/", "https://www.example.com/", ], redirectSignOut: [ "http://localhost:3000/", "https://www.example.com/", ], ...oauthConfig }, }, ...userPoolConfig }, },});
function App() { const [user, setUser] = useState<AuthUser | null>(null); const [error, setError] = useState<unknown>(null); const [customState, setCustomState] = useState<string | null>(null);
useEffect(() => { const unsubscribe = Hub.listen("auth", ({ payload }) => { switch (payload.event) { case "signInWithRedirect": getUser(); break; case "signInWithRedirect_failure": setError("An error has occurred during the Oauth flow."); break; case "customOAuthState": setCustomState(payload.data); break; } });
getUser();
return unsubscribe; }, []);
const getUser = async (): Promise<void> => { try { const currentUser = await getCurrentUser(); setUser(currentUser); } catch (error) { console.error(error); console.log("Not signed in"); } };
return ( <div className="App"> <button onClick={() => signInWithRedirect()}>Open Hosted UI</button> <button onClick={() => signOut()}>Sign Out</button> <div>{user?.username}</div> </div> );}import React, { useEffect, useState } from 'react';import { Amplify } from 'aws-amplify';import { Hub } from 'aws-amplify/utils';import { signInWithRedirect, signOut, getCurrentUser } from 'aws-amplify/auth';
Amplify.configure({ Auth: { Cognito: { loginWith: { oauth: { redirectSignIn: [ 'http://localhost:3000/', 'https://www.example.com/' ], redirectSignOut: [ 'http://localhost:3000/', 'https://www.example.com/' ], ...oauthConfig } }, ...userPoolConfig } }});
function App() { const [user, setUser] = useState(null); const [error, setError] = useState(null); const [customState, setCustomState] = useState(null);
useEffect(() => { const unsubscribe = Hub.listen('auth', ({ payload }) => { switch (payload.event) { case 'signInWithRedirect': getUser(); break; case 'signInWithRedirect_failure': setError('An error has occurred during the Oauth flow.'); break; case 'customOAuthState': setCustomState(payload.data); break; } });
getUser();
return unsubscribe; }, []);
const getUser = async () => { try { const currentUser = await getCurrentUser(); setUser(currentUser); } catch (error) { console.error(error); console.log('Not signed in'); } };
return ( <div className="App"> <button onClick={() => signInWithRedirect()}>Open Hosted UI</button> <button onClick={() => signInWithRedirect({ provider: 'Facebook' })}> Open Facebook </button> <button onClick={() => signInWithRedirect({ provider: 'Google' })}> Open Google </button> <button onClick={() => signInWithRedirect({ provider: 'Amazon' })}> Open Amazon </button> <button onClick={() => signInWithRedirect({ provider: 'Apple' })}> Open Apple </button> <button onClick={() => signOut()}>Sign Out</button> <div>{user?.username}</div> </div> );}サインアウト時にリダイレクト URL を指定する
複数のリダイレクト URL が設定されている場合、リダイレクト URL を選択するデフォルト動作をオーバーライドし、signOut を呼び出すときに選択したものを指定できます。提供されたリダイレクト URL は、設定されたリダイレクト URL の少なくとも 1 つと一致する必要があります。signOut にリダイレクト URL が指定されていない場合、現在のアプリドメインに基づいて選択されます。
import { Amplify } from 'aws-amplify';import { signOut } from 'aws-amplify/auth';
// Amplify 設定ファイルを通じて手動で提供される、または以下の URL が提供されていると仮定します// redirectSignOut: 'http://localhost:3000/,https://www.example.com/'
signOut({ global: false, oauth: { redirectUrl: 'https://www.example.com/' }});(マルチページアプリケーションに必須) リダイレクト後のソーシャルサインインを完了
マルチページアプリケーションを開発していて、リダイレクトされたページがサインインを開始したページと異なる場合、リダイレクトされたページに以下のコードを追加して、サインインが完了することを確認する必要があります:
import 'aws-amplify/auth/enable-oauth-listener';仕組みの詳細マルチページアプリケーションでソーシャルサインインを明示的に処理する必要がある理由
signInWithRedirect 関数をインポートして使用すると、ユーザーがアプリにリダイレクトバックされたときにソーシャルサインインを完了するリスナーが副作用として追加されます。これは単一ページアプリケーションではうまく機能しますが、マルチページアプリケーションでは、元々副作用として追加されたリスナーを含まないページにリダイレクトされる可能性があります。したがって、ログイン成功ページに特定の OAuth リスナーを含める必要があります。
カスタムプロバイダー
Cognito でデフォルトで提供されていないカスタムプロバイダーを使用する場合、カスタムプロバイダーの名前を含むオブジェクトを provider パラメータに渡すことができます。
import { signInWithRedirect } from 'aws-amplify/auth';
const provider = { custom: 'MyCustomOIDCProvider'}
function handleSignInClick() { signInWithRedirect({ provider })}ソーシャルサインインのための認証パラメータを使用して、バックエンドリソースをデプロイ
認証設定を作成または更新すると、Amplify はローカルで設定をセットアップしますが、バックエンド環境への変更を自動的にはデプロイしません。amplify push を実行してバックエンド環境に変更をデプロイする必要があります。
フロントエンドとバックエンドの継続的なデプロイを使用して、アプリを Amplify コンソールにデプロイできます。詳細については、これらの手順をご覧ください。
まとめ
ソーシャルプロバイダーのサインインを追加 ガイドが完了しました。このガイドでは、ソーシャル認証プロバイダーをセットアップし、ソーシャルサインイン用に Amplify Auth カテゴリを設定し、フロントエンドをセットアップする方法を学びました。これでユーザーはソーシャルプロバイダーアカウントを使用してアプリにサインインできます。
次のステップ
ソーシャルプロバイダーのサインインが完了したので、これらのワークフローをカスタマイズする方法について詳しく知ることができます。以下をお勧めします: