チュートリアル: 外部テナントで認証用の React SPA を作成する

このチュートリアルは、React シングルページ アプリケーション (特権アクセスのセキュリティ保護 (SPA)) の構築と、Microsoft Entra 管理センターを使った認証の準備について説明するシリーズのパート 2 です。 このシリーズのパート 1 では、外部テナントでアプリケーションを登録し、ユーザー フローを構成しました。 このチュートリアルでは、npm を使って React SPA を作成し、認証と認可に必要なファイルを作成する方法について説明します。

このチュートリアルでは、

  • Visual Studio Code で React プロジェクトを作成する
  • ID およびブートストラップのパッケージをインストールする
  • アプリケーションの設定を構成する

前提条件

React プロジェクトを作成する

  1. Visual Studio Code を開き、[ファイル]>[フォルダーを開く...] の順に選択します。プロジェクトを作成する場所に移動して選択します。

  2. [ターミナル]>[新しいターミナル] を選択して、新しいターミナルを開きます。

  3. 次のコマンドを実行して、新しい React プロジェクトを reactspalocal という名前で作成し、新しいディレクトリに移動して React プロジェクトを開始します。 既定では、アドレス http://localhost:3000/ で Web ブラウザーが開きます。 ブラウザーは開いたままで、変更が保存されるたびに再レンダリングされます。

    npx create-react-app reactspalocal
    cd reactspalocal
    npm start
    
  4. 追加のフォルダーとファイルを作成して、次のフォルダー構造を完成させます。

    reactspalocal
    ├─── public
    │   └─── index.html
    └───src
        ├─── components
        │   └─── DataDisplay.jsx
        │   └─── NavigationBar.jsx
        │   └─── PageLayout.jsx
        └───styles
        │   └─── App.css
        │   └─── index.css
        └─── utils
        │    └─── claimUtils.js
        └── App.jsx
        └── authConfig.js
        └── index.js
    

アプリの依存関係をインストールする

ユーザー認証を有効にするには、ID 関連の npm パッケージがプロジェクトにインストールされている必要があります。 プロジェクトのスタイル設定には、Bootstrap を使用します。

  1. [ターミナル] バーで、+ アイコンを選択して新しいターミナルを作成します。 新しいターミナル ウィンドウが開き、もう一方のターミナルをバックグラウンドで実行し続けることが可能になります。

  2. 必要に応じて、reactspalocal に移動し、そのターミナルに次のコマンドを入力して msalbootstrap のパッケージをインストールします。

    npm install @azure/msal-browser @azure/msal-react
    npm install react-bootstrap bootstrap
    

認証構成ファイル authConfig.js を作成する

  1. src フォルダーで authConfig.js を開き、次のコード スニペットを追加します。

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    
    import { LogLevel } from '@azure/msal-browser';
    
    /**
     * Configuration object to be passed to MSAL instance on creation.
     * For a full list of MSAL.js configuration parameters, visit:
     * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md 
     */
    
    export const msalConfig = {
        auth: {
            clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply.
            authority: 'https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/', // Replace the placeholder with your tenant subdomain 
            redirectUri: '/', // Points to window.location.origin. You must register this URI on Azure Portal/App Registration.
            postLogoutRedirectUri: '/', // Indicates the page to navigate after logout.
            navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
        },
        cache: {
            cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
            storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
        },
        system: {
            loggerOptions: {
                loggerCallback: (level, message, containsPii) => {
                    if (containsPii) {
                        return;
                    }
                    switch (level) {
                        case LogLevel.Error:
                            console.error(message);
                            return;
                        case LogLevel.Info:
                            console.info(message);
                            return;
                        case LogLevel.Verbose:
                            console.debug(message);
                            return;
                        case LogLevel.Warning:
                            console.warn(message);
                            return;
                        default:
                            return;
                    }
                },
            },
        },
    };
    
    /**
     * Scopes you add here will be prompted for user consent during sign-in.
     * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
     * For more information about OIDC scopes, visit:
     * https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
     */
    export const loginRequest = {
        scopes: [],
    };
    
    /**
     * An optional silentRequest object can be used to achieve silent SSO
     * between applications by providing a "login_hint" property.
     */
    // export const silentRequest = {
    //     scopes: ["openid", "profile"],
    //     loginHint: "example@domain.net"
    // };
    
  2. 次の値を、Azure portal の値に置き換えます。

    • Enter_the_Application_Id_Here の値を見つけ、Microsoft Entra 管理センターで登録したアプリのアプリケーション ID (clientId) に置き換えます。
    • [権限] で、Enter_the_Tenant_Subdomain_Here を見つけ、それをテナントのサブドメインに置き換えます。 たとえば、テナントのプライマリ ドメインが contoso.onmicrosoft.com の場合は、contoso を使用します。 テナント名がない場合は、テナントの詳細を読み取る方法を確認してください
  3. ファイルを保存します。

カスタム ドメイン URL を使用する (省略可能)

カスタム ドメインを使用して、認証 URL を完全にブランド化します。 ユーザーの視点から見ると、認証プロセスの間、ユーザーは ciamlogin.com ドメイン名にリダイレクトされず、あなたのドメインにとどまります。

カスタム ドメインを使用するには、以下の手順を使用します。

  1. 外部テナント内のアプリに対するカスタム URL ドメインの有効化」の手順を使用して、外部テナントに対してカスタム ドメイン URL を有効にします。

  2. 次に、authConfig.js ファイルで、auth オブジェクトを見つけて、次のようにします。

    1. authority プロパティの値を https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here に更新します。 Enter_the_Custom_Domain_Here をカスタム ドメイン URL に、Enter_the_Tenant_ID_Here をテナント ID に置き換えます。 テナント ID がわからない場合は、テナントの詳細を読み取る方法を確認してください。
    2. [Enter_the_Custom_Domain_Here] という値を持つ knownAuthorities プロパティを追加します。

カスタム ドメイン URL が login.contoso.com、テナント ID が aaaabbbb-0000-cccc-1111-dddd2222eeee の場合、authConfig.js ファイルに変更を加えた後には、ファイルは次のスニペットのようになるはずです。

//...
const msalConfig = {
    auth: {
        authority: process.env.AUTHORITY || 'https://login.contoso.com/aaaabbbb-0000-cccc-1111-dddd2222eeee', 
        knownAuthorities: ["login.contoso.com"],
        //Other properties
    },
    //...
};

index.js を修正して認証プロバイダーを含める

認証を必要とするアプリのすべての部分を MsalProvider コンポーネントにラップする必要があります。 PublicClientApplication をインスタンス化して MsalProvider に渡します。

  1. "src" フォルダーで、"index.js" を開き、msal パッケージとブートストラップのスタイルを使用するために、ファイルの内容を次のコード スニペットに置き換えます。

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    import { PublicClientApplication, EventType } from '@azure/msal-browser';
    import { msalConfig } from './authConfig';
    
    import 'bootstrap/dist/css/bootstrap.min.css';
    import './styles/index.css';
    
    /**
     * MSAL should be instantiated outside of the component tree to prevent it from being re-instantiated on re-renders.
     * For more, visit: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
     */
    const msalInstance = new PublicClientApplication(msalConfig);
    
    // Default to using the first account if no account is active on page load
    if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) {
        // Account selection logic is app dependent. Adjust as needed for different use cases.
        msalInstance.setActiveAccount(msalInstance.getActiveAccount()[0]);
    }
    
    // Listen for sign-in event and set active account
    msalInstance.addEventCallback((event) => {
        if (event.eventType === EventType.LOGIN_SUCCESS && event.payload.account) {
            const account = event.payload.account;
            msalInstance.setActiveAccount(account);
        }
    });
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
        <App instance={msalInstance}/>
    );
    

次のステップ