MSAL React のフック

MSAL React のフックは、機能コンポーネント内で MSAL 機能と React 状態およびライフサイクル メソッドを使用できる関数です。 主なフックは、 useAccountuseIsAuthenticateduseMsal、および useMsalAuthenticationです。 この記事では、これらの各フックの使用方法について説明します。

useAccount フック

useAccount フックは、accountIdentifier パラメーターを受け取り、サインインしている場合はそのアカウントのAccountInfo オブジェクトを返し、サインインしていない場合はnullします。 アカウント識別子が指定されていない場合、現在 のアクティブなアカウント が返されます。 AccountInfo@azure/msal-browser ドキュメントで返される オブジェクトの詳細を確認できます。

const accountIdentifier = {
    localAccountId: "example-local-account-identifier",
    homeAccountId: "example-home-account-identifier"
    username: "example-username" // We do not recommend relying only on username
}

const accountInfo = useAccount(accountIdentifier);

useIsAuthenticated フック

useIsAuthenticated フックは、アカウントがサインインしているかどうかを示すブール値を返します。 必要に応じて、特定のアカウントがサインインしているかどうかを知る必要がある場合に指定できる accountIdentifier オブジェクトを受け入れます。

アカウントが現在サインインしているかどうかを確認する

次のスニペットでは、useIsAuthenticated パッケージの@azure/msal-react フックを使用します。 その後、コンポーネントは、ユーザーがサインインしているかどうかに基づいて、条件付きでメッセージをレンダリングします。

import React from 'react';
import { useIsAuthenticated } from "@azure/msal-react";

export function App() {
    const isAuthenticated = useIsAuthenticated();

    return (
        <React.Fragment>
            <p>Anyone can see this paragraph.</p>
            {isAuthenticated && (
                <p>At least one account is signed in!</p>
            )}
            {!isAuthenticated && (
                <p>No users are signed in!</p>
            )}
        </React.Fragment>
    );
}

特定のユーザーがサインインしているかどうかを判断する

次のスニペットでは、useIsAuthenticated パッケージの@azure/msal-react フックを使用して、特定のユーザーがサインインしているかどうかを判断します。

import React from 'react';
import { useIsAuthenticated } from "@azure/msal-react";

export function App() {
    const accountIdentifiers = {
        localAccountId: "example-local-account-identifier",
        homeAccountId: "example-home-account-identifier",
        username: "example-username"
    }

    const isAuthenticated = useIsAuthenticated(accountIdentifiers);

    return (
        <React.Fragment>
            <p>Anyone can see this paragraph.</p>
            {isAuthenticated && (
                <p>User with specified localAccountId is signed in!</p>
            )}
            {!isAuthenticated && (
                <p>User with specified localAccountId is not signed in!</p>
            )}
        </React.Fragment>
    );
}

useMsal フック

useMsal フックはコンテキストを返します。 これは、 PublicClientApplication インスタンスにアクセスする必要がある場合、現在サインインしているアカウントの一覧、またはログインまたはその他の操作が現在進行中かどうかを知る必要がある場合に使用できます。

注: accountsによって返されるuseMsal値は、アカウントが追加または削除された場合にのみ更新され、要求が更新された場合は更新されません。 現在のユーザーの更新された要求にアクセスする必要がある場合は、代わりに useAccount フックまたは呼び出し acquireTokenSilent を使用します。

import { useState, useEffect } from "react";
import { useMsal } from "@azure/msal-react";
import { InteractionStatus } from "@azure/msal-browser";

const { instance, accounts, inProgress } = useMsal();
const [loading, setLoading] = useState(false);
const [apiData, setApiData] = useState(null);

useEffect(() => {
    if (!loading && inProgress === InteractionStatus.None && accounts.length > 0) {
        if (apiData) {
            // Skip data refresh if already set - adjust logic for your specific use case
            return;
        }

        const tokenRequest = {
            account: accounts[0], // This is an example - Select account based on your app's requirements
            scopes: ["User.Read"]
        }

        // Acquire an access token
        instance.acquireTokenSilent(tokenRequest).then((response) => {
            // Call your API with the access token and return the data you need to save in state
            callApi(response.accessToken).then((data) => {
                setApiData(data);
                setLoading(false);
            });
        }).catch(async (e) => {
            // Catch interaction_required errors and call interactive method to resolve
            if (e instanceof InteractionRequiredAuthError) {
                await instance.acquireTokenRedirect(tokenRequest);
            }

            throw e;
        });
    }
}, [inProgress, accounts, instance, loading, apiData]);

if (loading || inProgress === InteractionStatus.Login) {
    // Render loading component
} else if (apiData) {
    // Render content that depends on data from your API
}

useMsalAuthentication フック

useMsalAuthentication フックは、ユーザーがまだサインインしていない場合はログインを開始し、それ以外の場合はトークンの取得を試みます。

入力パラメーター

useMsalAuthentication フックには、いくつかの異なる入力パラメーターを指定できます。

  • interactionType - (None、Popup、Redirect、または Silent) は、対話が必要な場合にトークンまたはログインを取得する方法を指定します (サイレント オプションには、以下で説明する追加の考慮事項があることに注意してください)。
  • request オブジェクト - (省略可能) ログインまたはトークン取得呼び出しで使用される追加のパラメーターを指定します
  • accountIdentifiers - オブジェクトは、ログインまたはトークンを取得する必要があるユーザーをフックに通知するために使用されます。

リターン プロパティ

  • result - 最後に成功したログインまたはトークンの取得の結果。 このフックは、1 回だけ自動的にログインまたはトークンを取得しようとします。 必要に応じ、 login または acquireToken 関数を呼び出してこの値を更新するのは、アプリケーションの責任です。
  • error - ログインまたはトークンの取得中にエラーが発生した場合、このプロパティにはエラーに関する情報が含まれます。 このフックによって返される login または acquireToken 関数を使用して再試行できます。 error プロパティは、次回成功したログインまたはトークンの取得時にクリアされます。
  • login - 失敗したログインを再試行するために使用できる関数。 resultプロパティとerrorプロパティが更新されます。
  • acquireToken - 保護された API を呼び出す前に新しいアクセス トークンを取得するために使用できる関数。 resultプロパティとerrorプロパティが更新されます。

"サイレント" 対話の種類を渡すと、非表示の iframe を開き、Microsoft Entra IDで既存のセッションを再利用しようとするssoSilentが呼び出されます。 これは、Safari などのサード パーティの Cookie をブロックするブラウザーでは機能しません。 さらに、"Silent" 型を使用する場合は、要求オブジェクトが必要です。 ユーザーのサインイン情報が既にある場合は、 loginHint または省略可能なパラメーター sid 渡して、特定のアカウントにサインインできます。 注: ユーザーのセッションに関する情報を提供せずにを使用する場合は、ssoSilentがあります。

ssoSilent

サイレントを使用する場合は、エラーをキャッチし、フォールバックとして対話型ログインを試みる必要があります。

import React, { useEffect } from 'react';

import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal, useMsalAuthentication } from "@azure/msal-react";
import { InteractionType, InteractionRequiredAuthError } from '@azure/msal-browser';

function App() {
    const request = {
        loginHint: "name@example.com",
        scopes: ["User.Read"]
    }
    const { login, result, error } = useMsalAuthentication(InteractionType.Silent, request);

    useEffect(() => {
        if (error instanceof InteractionRequiredAuthError) {
            login(InteractionType.Popup, request);
        }
    }, [error]);

    const { accounts } = useMsal();

    return (
        <React.Fragment>
            <p>Anyone can see this paragraph.</p>
            <AuthenticatedTemplate>
                <p>Signed in as: {accounts[0]?.username}</p>
            </AuthenticatedTemplate>
            <UnauthenticatedTemplate>
                <p>No users are signed in!</p>
            </UnauthenticatedTemplate>
        </React.Fragment>
    );
}

export default App;

特定のユーザーの例

特定のユーザーがサインインしていることを確認する場合は、 accountIdentifiers オブジェクトを指定します。

import React from 'react';
import { useMsalAuthentication } from "@azure/msal-react";
import { InteractionType } from '@azure/msal-browser';

export function App() {
    const accountIdentifiers = {
        username: "example-username"
    }
    const request = {
        loginHint: "example-username",
        scopes: ["User.Read"]
    }
    const { login, result, error } = useMsalAuthentication(InteractionType.Popup, request, accountIdentifiers);

    return (
        <React.Fragment>
            <p>Anyone can see this paragraph.</p>
            <AuthenticatedTemplate username="example-username">
                <p>Example user is signed in!</p>
            </AuthenticatedTemplate>
            <UnauthenticatedTemplate username="example-username">
                <p>Example user is not signed in!</p>
            </UnauthenticatedTemplate>
        </React.Fragment>
    );
}

こちらも参照ください

MSAL Browser で公開 PublicClientApplication API のドキュメントを確認できます。