次の方法で共有


チュートリアル: React シングルページ アプリケーションを作成し、認証用に準備する

適用対象: 白いチェック マーク記号が付いた緑の円。 従業員テナント 白いチェック マーク記号が付いた緑の円。 外部テナント (詳細はこちら)

このチュートリアルでは、React シングルページ アプリケーション (SPA) を構築し、Microsoft ID プラットフォームを使用して認証用に準備します。 このチュートリアルでは、 npmを使用して React SPA を作成し、認証と承認に必要なファイルを作成し、テナントの詳細をソース コードに追加する方法について説明します。 このアプリケーションは、従業員テナントの従業員または外部テナントを使用している顧客に使用できます。

このチュートリアルでは、次の操作を行います。

  • 新しい React プロジェクトを作成する
  • 認証に必要なパッケージをインストールする
  • ファイル構造を作成し、サーバー ファイルにコードを追加する
  • 認証構成ファイルにテナントの詳細を追加する

前提条件

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

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

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

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

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

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

ID およびブートストラップのパッケージをインストールする

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

  1. [ターミナル] バーで、+ アイコンを選択して新しいターミナルを作成します。 別のターミナル ウィンドウが開き、前のノード ターミナルがバックグラウンドで実行され続けます。

  2. 正しいディレクトリが選択されていることを確認し (reactspalocal)、ターミナルに次のように入力して、関連する msalbootstrap パッケージをインストールします。

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

テナントの詳細を MSAL 構成に追加する

authConfig.js ファイルには認証フローの構成設定が含まれており、認証に必要な設定でMSAL.js を構成するために使用されます。

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

    
     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://login.microsoftonline.com/Enter_the_Tenant_Info_Here', // Replace the placeholder with your tenant info
             redirectUri: 'http://localhost:3000/redirect', // Points to window.___location.origin. You must register this URI on Microsoft Entra admin center/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/en-us/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. 次の値を Microsoft Entra 管理センターから取得した値に置き換えます。

    • clientId - アプリケーションの識別子 。クライアントとも呼ばれます。 Enter_the_Application_Id_Here を、登録したアプリケーションの概要ページから先ほど記録したアプリケーション (クライアント) ID の値に置き換えます。
    • authority - これは 2 つの部分で構成されます。
      • "インスタンス" はクラウド プロバイダーのエンドポイントです。 各国のクラウドの利用可能なさまざまなエンドポイントで確認します。
      • "テナント ID" は、アプリケーションが登録されているテナントの識別子です。 Enter_the_Tenant_Info_Here を、登録したアプリケーションの概要ページから先ほど記録したディレクトリ (テナント) ID の値に置き換えます。
  3. ファイルを保存します。

認証プロバイダーを追加する

msal パッケージは、アプリケーションで認証を提供するために使用されます。 msal-browser パッケージは認証フローを処理するために使用され、msal-react パッケージは msal-browser を React と統合するために使用されます。 addEventCallback は、ユーザーが正常にログインしたときなど、認証プロセス中に発生するイベントをリッスンするために使用されます。 setActiveAccountメソッドは、アプリケーションのアクティブなアカウントを設定するために使用されます。これは、表示するユーザーの情報を決定するために使用されます。

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

    import React from 'react';
    import { createRoot } 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 = createRoot(document.getElementById('root'));
    root.render(
        <App instance={msalInstance}/>
    );
    
  2. ファイルを保存します。

これらのパッケージの詳細については、 msal-browsermsal-reactのドキュメントを参照してください。

メイン アプリケーション コンポーネントを追加する

認証を必要とするアプリのすべての部分を MsalProvider コンポーネントにラップする必要があります。 instance フックを呼び出してuseMsal インスタンスを取得するPublicClientApplication変数を設定し、それをMsalProviderに渡します。 MsalProvider コンポーネントを使用すると、React の Context API を使用して、アプリ全体でPublicClientApplication インスタンスを使用できるようになります。 MsalProviderの下にあるすべてのコンポーネントは、コンテキストだけでなく、PublicClientApplicationによって提供されるすべてのフックとコンポーネントを介してmsal-react インスタンスにアクセスできます。

  1. src フォルダーで App.jsx を開き、ファイルの内容を次のコード スニペットに置き換えます。

    import { MsalProvider, AuthenticatedTemplate, useMsal, UnauthenticatedTemplate } from '@azure/msal-react';
    import { Container, Button } from 'react-bootstrap';
    import { PageLayout } from './components/PageLayout';
    import { IdTokenData } from './components/DataDisplay';
    import { loginRequest } from './authConfig';
    
    import './styles/App.css';
    
    /**
    * Most applications will need to conditionally render certain components based on whether a user is signed in or not. 
    * msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will 
    * only render their children if a user is authenticated or unauthenticated, respectively. For more, visit:
    * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
    */
    const MainContent = () => {
        /**
        * useMsal is hook that returns the PublicClientApplication instance,
        * that tells you what msal is currently doing. For more, visit:
        * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/hooks.md
        */
        const { instance } = useMsal();
        const activeAccount = instance.getActiveAccount();
    
        const handleRedirect = () => {
            instance
                .loginRedirect({
                    ...loginRequest,
                    prompt: 'create',
                })
                .catch((error) => console.log(error));
        };
        return (
            <div className="App">
                <AuthenticatedTemplate>
                    {activeAccount ? (
                        <Container>
                            <IdTokenData idTokenClaims={activeAccount.idTokenClaims} />
                        </Container>
                    ) : null}
                </AuthenticatedTemplate>
                <UnauthenticatedTemplate>
                    <Button className="signInButton" onClick={handleRedirect} variant="primary">
                        Sign up
                    </Button>
                </UnauthenticatedTemplate>
            </div>
        );
    };
    
    
    /**
    * msal-react is built on the React context API and all parts of your app that require authentication must be 
    * wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication 
    * then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the 
    * PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit:
    * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
    */
    const App = ({ instance }) => {
        return (
            <MsalProvider instance={instance}>
                <PageLayout>
                    <MainContent />
                </PageLayout>
            </MsalProvider>
        );
    };
    
    export default App;
    
  2. ファイルを保存します。

次のステップ