次の方法で共有


シングルページ アプリケーション:API を呼び出すトークンを取得する

適用対象: 白いチェック マーク記号が付いた緑の円。 従業員テナント 灰色の X 記号が付いた白い円。 外部テナント (詳細情報)

MSAL.js を使用して API 用のトークンを取得するパターンは、acquireTokenSilent メソッドを使用してサイレント トークン要求を最初に試行することです。 このメソッドが呼び出されると、ライブラリでは、まずブラウザー ストレージ内のキャッシュを調べて、期限切れでないアクセス トークンが存在するかどうかを確認し、それを返します。 アクセス トークンが見つからないか、見つかったアクセス トークンの有効期限が切れている場合は、その更新トークンを使用して新しいアクセス トークンを取得しようとします。 更新トークンの 24 時間の有効期間も期限切れになった場合、MSAL.js は非表示の iframe を開き、Microsoft Entra ID との既存のアクティブなセッション (存在する場合) を利用して新しい認可コードをサイレントに要求します。その後、これは新しいトークン セット (アクセスおよび更新トークン) と交換されます。

シングル サインオン (SSO) セッションおよび Microsoft Entra ID 内のトークン有効期間値の詳細については、トークンの有効期間に関するページを参照してください。 MSAL.js キャッシュ検索ポリシーの詳細については、「アクセス トークンの取得」を参照してください。

Microsoft Entra ID へのサイレント トークン要求は、パスワードの変更や条件付きアクセス ポリシーの更新などの理由により、失敗する場合があります。 エラーは多くの場合、更新トークンの 24 時間の有効期限が切れ、ブラウザーがサード パーティの Cookie をブロックしていることが原因で発生します。この場合、非表示の iframe を使用してユーザーの認証を継続することができなくなります。 このような場合は、トークンを取得するために、(ユーザーにプロンプトを表示できる) 対話型のメソッドのいずれかを呼び出す必要があります。

ポップアップ エクスペリエンスか、リダイレクト エクスペリエンスを選択

ポップアップまたはリダイレクト エクスペリエンスのいずれを選択するかは、ご利用のアプリケーション フローに依存します。

  • 認証中にユーザーにメイン アプリケーション ページから移動してほしくない場合は、ポップアップ メソッドをお勧めします。 認証リダイレクトはポップアップ ウィンドウで行われるため、メイン アプリケーションの状態は保持されます。
  • ポップアップウィンドウが無効になっているブラウザの制約またはポリシーがある場合は、リダイレクト方法を使用できます。 Internet Explorer のポップアップ ウィンドウには既知の問題 があるので、Internet Explorer ブラウザーでは、リダイレクト メソッドを使用してください。

アクセス トークン要求を作成するときにアクセス トークンに含める API スコープを設定することができます。 要求されたすべてのスコープがアクセス トークンに付与されるとは限りません。 これは、ユーザーの同意によって異なります。

ポップアップ ウィンドウを使用してトークンを取得する

次のコードでは、前に説明したパターンと、ポップアップ エクスペリエンスのメソッドを組み合わせています。

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

function ProtectedComponent() {
  const { instance, inProgress, accounts } = useMsal();
  const [apiData, setApiData] = useState(null);

  useEffect(() => {
    if (!apiData && inProgress === InteractionStatus.None) {
      const accessTokenRequest = {
        scopes: ["user.read"],
        account: accounts[0],
      };
      instance
        .acquireTokenSilent(accessTokenRequest)
        .then((accessTokenResponse) => {
          // Acquire token silent success
          let accessToken = accessTokenResponse.accessToken;
          // Call your API with token
          callApi(accessToken).then((response) => {
            setApiData(response);
          });
        })
        .catch((error) => {
          if (error instanceof InteractionRequiredAuthError) {
            instance
              .acquireTokenPopup(accessTokenRequest)
              .then(function (accessTokenResponse) {
                // Acquire token interactive success
                let accessToken = accessTokenResponse.accessToken;
                // Call your API with token
                callApi(accessToken).then((response) => {
                  setApiData(response);
                });
              })
              .catch(function (error) {
                // Acquire token interactive failure
                console.log(error);
              });
          }
          console.log(error);
        });
    }
  }, [instance, accounts, inProgress, apiData]);

  return <p>Return your protected content here: {apiData}</p>;
}

function App() {
  return (
    <AuthenticatedTemplate>
      <ProtectedComponent />
    </AuthenticatedTemplate>
  );
}

または、React コンポーネントの外部でトークンを取得する必要がある場合は、acquireTokenSilent を呼び出すことはできますが、失敗した場合には対話にフォールバックしないでください。 コンポーネント ツリーの MsalProvider コンポーネントの下で、すべての対話が行われます。

// MSAL.js v2 exposes several account APIs, logic to determine which account to use is the responsibility of the developer
const account = publicClientApplication.getAllAccounts()[0];

const accessTokenRequest = {
  scopes: ["user.read"],
  account: account,
};

// Use the same publicClientApplication instance provided to MsalProvider
publicClientApplication
  .acquireTokenSilent(accessTokenRequest)
  .then(function (accessTokenResponse) {
    // Acquire token silent success
    let accessToken = accessTokenResponse.accessToken;
    // Call your API with token
    callApi(accessToken);
  })
  .catch(function (error) {
    //Acquire token silent failure
    console.log(error);
  });

リダイレクトを使用してトークンを取得する

acquireTokenSilent が失敗した場合は、acquireTokenRedirect にフォールバックします。 この方法により、フルフレーム リダイレクトが開始され、応答はアプリケーションに戻るときに処理されます。 リダイレクトから戻った後にこのコンポーネントがレンダリングされるときに、トークンがキャッシュからプルされるため、acquireTokenSilent は成功します。

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

function ProtectedComponent() {
  const { instance, inProgress, accounts } = useMsal();
  const [apiData, setApiData] = useState(null);

  useEffect(() => {
    const accessTokenRequest = {
      scopes: ["user.read"],
      account: accounts[0],
    };
    if (!apiData && inProgress === InteractionStatus.None) {
      instance
        .acquireTokenSilent(accessTokenRequest)
        .then((accessTokenResponse) => {
          // Acquire token silent success
          let accessToken = accessTokenResponse.accessToken;
          // Call your API with token
          callApi(accessToken).then((response) => {
            setApiData(response);
          });
        })
        .catch((error) => {
          if (error instanceof InteractionRequiredAuthError) {
            instance.acquireTokenRedirect(accessTokenRequest);
          }
          console.log(error);
        });
    }
  }, [instance, accounts, inProgress, apiData]);

  return <p>Return your protected content here: {apiData}</p>;
}

function App() {
  return (
    <AuthenticatedTemplate>
      <ProtectedComponent />
    </AuthenticatedTemplate>
  );
}

または、React コンポーネントの外部でトークンを取得する必要がある場合は、acquireTokenSilent を呼び出すことはできますが、失敗した場合には対話にフォールバックしないでください。 コンポーネント ツリーの MsalProvider コンポーネントの下で、すべての対話が行われます。

// MSAL.js v2 exposes several account APIs, logic to determine which account to use is the responsibility of the developer
const account = publicClientApplication.getAllAccounts()[0];

const accessTokenRequest = {
  scopes: ["user.read"],
  account: account,
};

// Use the same publicClientApplication instance provided to MsalProvider
publicClientApplication
  .acquireTokenSilent(accessTokenRequest)
  .then(function (accessTokenResponse) {
    // Acquire token silent success
    let accessToken = accessTokenResponse.accessToken;
    // Call your API with token
    callApi(accessToken);
  })
  .catch(function (error) {
    //Acquire token silent failure
    console.log(error);
  });

次のステップ