ユーザーセッションと認証情報の管理
Amplify Auth は、現在のユーザーセッションとトークンへのアクセスを提供し、ユーザーの情報を取得してユーザーが有効なセッションで署名されているかどうかを判断し、アプリへのアクセスを制御するのに役立ちます。トークンと有効期限を管理し、セッションを無効にすることができます。このガイドでは、ユーザーのセッションを取得する方法と、利用可能なトークン管理オプションについて説明します。
始める前に、以下が必要です:
- Auth カテゴリが設定された Amplify プロジェクト
- インストールおよび設定された Amplify ライブラリ
- サインインしたテストユーザー
現在認証されているユーザーを取得する
getCurrentUser API を使用して、username、userId、signInDetails を含む現在認証されているユーザーに関する情報を取得できます。
import { getCurrentUser } from 'aws-amplify/auth';
async function currentAuthenticatedUser() { try { const { username, userId, signInDetails } = await getCurrentUser(); console.log(`The username: ${username}`); console.log(`The userId: ${userId}`); console.log(`The signInDetails: ${signInDetails}`); } catch (err) { console.log(err); }}import { getCurrentUser } from 'aws-amplify/auth';
async function currentAuthenticatedUser() { try { const { username, userId, signInDetails } = await getCurrentUser(); console.log(`The username: ${username}`); console.log(`The userId: ${userId}`); console.log(`The signInDetails: ${signInDetails}`); } catch (err) { console.log(err); }}このメソッドを使用して、ユーザーがサインインしているかどうかを確認できます。ユーザーが認証されていない場合、エラーがスローされます。
ユーザーセッションを取得する
ユーザーのセッションは、サインインした状態で、アプリへのアクセスを許可します。ユーザーがサインインすると、認証情報が一時的なアクセストークンと交換されます。セッション詳細を取得してこれらのトークンにアクセスし、この情報を使用してユーザーアクセスを検証するか、そのユーザーに固有のアクションを実行できます。
セッション詳細のみが必要な場合は、fetchAuthSession API を使用できます。これは JWT (JSON Web Tokens) を含む tokens オブジェクトを返します。
詳細を表示トークンオブジェクトが含む内容とトークンの仕組みを確認する
tokens オブジェクト内のこのセキュアな情報には、以下が含まれます:
idToken- ユーザー名やメールなどのユーザー ID 情報を含む JWT。ユーザーを認証するために使用されます。accessToken- 保護された AWS リソースと API にアクセスするために使用される JWT。認可されたスコープを含みます。
Amazon Cognito トークンは、ユーザーサインイン時に有効期限付きの一時的なアクセスおよび ID トークンを生成することで機能します。トークンはユーザープールに対して検証され、有効期限切れになるまでアクセスが認可されます。
import { fetchAuthSession } from 'aws-amplify/auth';
async function currentSession() { try { const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {}; } catch (err) { console.log(err); }}import { fetchAuthSession } from 'aws-amplify/auth';
async function currentSession() { try { const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {}; } catch (err) { console.log(err); }}セッションのリフレッシュ
fetchAuthSession API は、認証トークンが有効期限切れになり、有効な refreshToken が存在する場合、ユーザーのセッションを自動的にリフレッシュします。さらに、forceRefresh フラグを有効にして fetchAuthSession API を呼び出すことで、セッションを明示的にリフレッシュすることもできます。
import { fetchAuthSession } from 'aws-amplify/auth';
async function currentSession() { try { const { tokens } = await fetchAuthSession({ forceRefresh: true }); console.log(tokens); } catch (err) { console.log(err); }}ソーシャルプロバイダーでセッションをリフレッシュする
ソーシャルプロバイダーで認証する場合にユーザーのセッションをリフレッシュするには、Amplify 設定で code grant OAuth フローを使用する必要があります。
Amplify.configure({ Auth: { Cognito: { ...cognitoConfig, loginWith: { oauth: { ...oauthConfig, responseType: "code", }, }, }, },})トークン管理オプションについて理解する
トークンキーはセキュリティを向上させるために自動的にローテーションされますが、保存方法を更新したり、リフレッシュレートと有効期限をカスタマイズしたり、サインアウト時にトークンを無効にしたりできます。
トークン保存メカニズムを更新する
ストレージメカニズムを更新して、アプリケーション内でトークンがどこにどのように保持されるかを選択できます。デフォルトのオプションは localStorage です。さらに、sessionStorage、sharedInMemoryStorage、または CookieStorage オプションをインポートすることもできます。
独自のメカニズムをカスタマイズする場合は、KeyValueStorageInterface インターフェイスをインポートして、独自のクラスに実装できます。
ブラウザのローカルストレージ
Amplify では localStorage がデフォルトのストレージメカニズムです。ブラウザの localStorage にトークンを保存します。このローカルストレージはブラウザセッションとタブ間で保持されます。以下を呼び出すことで、明示的にこのストレージに設定できます:
import { Amplify, type ResourcesConfig } from 'aws-amplify';import { defaultStorage } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig: ResourcesConfig['Auth'] = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage);import { Amplify } from 'aws-amplify';import { defaultStorage } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage);Cookie ストレージ
CookieStorage はブラウザの Cookies にトークンを保存します。Cookie はブラウザセッションとタブ間で保持されます。以下を呼び出すことで、明示的にこのストレージに設定できます:
import { Amplify, type ResourcesConfig } from 'aws-amplify';import { CookieStorage } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig: ResourcesConfig['Auth'] = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());import { Amplify } from 'aws-amplify';import { CookieStorage } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());ブラウザセッションストレージ
sessionStorage はブラウザの sessionStorage にトークンを保存し、タブが閉じられるとこれらのトークンは削除されます。このストレージメカニズムの利点は、セッションがブラウザが開いている限りのみ続き、ユーザーがタブを閉じたときにユーザーをサインアウトできることです。このストレージに更新するには、以下を呼び出します:
import { Amplify, type ResourcesConfig } from 'aws-amplify';import { sessionStorage } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig: ResourcesConfig['Auth'] = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(sessionStorage);import { Amplify } from 'aws-amplify';import { sessionStorage } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(sessionStorage);カスタムストレージ
ストレージインターフェイスを実装するクラスを作成して、独自のカスタムストレージメカニズムを実装できます。以下はメモリストレージを使用する例です:
import { Amplify, type ResourcesConfig } from 'aws-amplify';import { KeyValueStorageInterface } from 'aws-amplify/utils';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig: ResourcesConfig['Auth'] = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
class MyCustomStorage implements KeyValueStorageInterface { storageObject: Record<string, string> = {}; async setItem(key: string, value: string): Promise<void> { this.storageObject[key] = value; } async getItem(key: string): Promise<string | null> { return this.storageObject[key]; } async removeItem(key: string): Promise<void> { delete this.storageObject[key]; } async clear(): Promise<void> { this.storageObject = {}; }}
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(new MyCustomStorage());import { Amplify } from 'aws-amplify';import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig = { Cognito: { userPoolId: 'your_user_pool_id', userPoolClientId: 'your_user_pool_client_id' }};
class MyCustomStorage { storageObject = {}; async setItem(key, value) { this.storageObject[key] = value; } async getItem(key) { return this.storageObject[key]; } async removeItem(key) { delete this.storageObject[key]; } async clear() { this.storageObject = {}; }}
Amplify.configure({ Auth: authConfig});
cognitoUserPoolsTokenProvider.setKeyValueStorage(new MyCustomStorage());現在のユーザーセッションを取得すると、トークンはカスタムロケーションに保存されます。
トークンを無効にする
トークン無効化は新しい Cognito ユーザープールクライアントではデフォルトで有効になっていますが、既存のクライアントを使用している場合は、有効にする必要がある場合があります。これにより、そのリフレッシュトークンによって以前に発行されたすべてのアクセストークンが無効になります。
トークンを無効にするには、signOut({ global: true }) でグローバルサインアウトを設定して、すべてのデバイスからユーザーをグローバルにサインアウトできます。
トークンの保存および管理方法を更新することで、アプリのユーザーエクスペリエンスを変更できるようになりました。
まとめ
おめでとうございます!ユーザーセッションと認証情報の管理ガイドを完了しました。このガイドでは、現在認証されているユーザー、ユーザーのセッション詳細を取得する方法、およびこれらのユーザー認証情報を管理する方法を確認しました。
次のステップ
認証情報の管理方法を更新したので、サインインおよびサインアウトワークフローをさらに改善し、これらの Auth イベントをリッスンする方法を更新することもできます。以下についてさらに詳しく学ぶことをお勧めします: