共用方式為


教學課程:在外部租使用者中建立 React SPA 以進行驗證

本教學課程是一系列的第 2 部分,示範如何建置 React 單頁應用程式(保護特殊許可權存取 (SPA),並準備使用 Microsoft Entra 系統管理中心進行驗證。 在本系列的第 1 部分中,您已在外部租用戶中註冊應用程式並設定使用者流程。 本教學課程示範如何使用 和 建立驗證和授權所需的檔案來建立 React SPA npm

在本教學課程中:

  • 在 Visual Studio Code 中建立 React 專案
  • 安裝身分識別和啟動套件
  • 設定應用程式設定

必要條件

建立 React 專案

  1. 開啟 Visual Studio Code,選取 [檔案]>[開啟資料夾...]。瀏覽至並選取您要在其中建立專案的位置。

  2. 選取 [終端機]>[新增終端機] 來開啟新的終端機。

  3. 執行下列命令來建立名為 reactspalocal 的新 React 專案,請變更為新的目錄,然後啟動 React 專案。 網頁瀏覽器預設會以地址 http://localhost:3000/ 開啟。 瀏覽器會保持開啟狀態,並針對每個已儲存的變更重新調整。

    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
    

安裝應用程式相依性

身分識別相關 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 入口網站的值:

    • 尋找 Enter_the_Application_Id_Here 值,並將其取代為您在 Microsoft Entra 系統管理中心所註冊應用程式的 應用程式識別碼 (clientId)
    • [授權單位] 中,尋找 Enter_the_Tenant_Subdomain_Here 並將它取代為您的租用戶的子域。 例如,如果您的租用戶主要網域是 contoso.onmicrosoft.com,請使用 contoso。 如果您沒有租用戶名稱,請了解如何讀取租用戶詳細資料
  3. 儲存檔案。

使用自訂網域 URL (選擇性 )

使用自定義網域來完整品牌驗證 URL。 從用戶的觀點來看,用戶在驗證程序期間會保留在網域上,而不是重新導向至 ciamlogin.com 功能變數名稱。

使用下列步驟來使用自訂網域:

  1. 使用為外部租使用者中的應用程式啟用自定義 URL 網域中的步驟,為您的外部租使用者啟用自定義網域 URL。

  2. 在您的 authConfig.js 檔案中,找出 then auth object,然後:

    1. 將屬性的值 authority 更新為 https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_HereEnter_the_Custom_Domain_Here取代為您的自訂網域 URL,並以Enter_the_Tenant_ID_Here您的租使用者識別碼取代 。 如果您沒有租使用者標識碼,請瞭解如何 閱讀您的租使用者詳細數據
    2. 新增 knownAuthorities 具有值 [Enter_the_Custom_Domain_Here] 的屬性。

對authConfig.js檔案進行變更之後,如果您的自定義網域 URL 已 login.contoso.com,且您的租用戶標識符為 aaaabbbb-0000-cccc-1111-dddd2222eeee,則您的檔案看起來應該類似下列代碼段:

//...
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}/>
    );
    

後續步驟