分享方式:


教學課程:建立 React 單頁應用程式並準備進行驗證

註冊完成之後,可以使用整合式開發環境 (IDE) 建立 React 專案。 本教學課程示範如何使用 npm 建立單頁 React 應用程式,以及如何建立驗證和授權所需的檔案。

在本教學課程中:

  • 建立新的 React 專案
  • 設定應用程式設定
  • 安裝身分識別和啟動套件
  • 將驗證程式碼新增至應用程式

必要條件

建立新的 React 專案

使用下列索引標籤在 IDE 內建立 React 專案。

  1. 開啟 Visual Studio,然後選取 [建立新專案]

  2. 搜尋並選擇獨立 JavaScript React 專案範本,然後選取 [下一步]

  3. 輸入專案名稱,例如 reactspalocal

  4. 選擇專案的位置或接受預設選項,然後選取 [下一步]

  5. 在 [其他資訊] 中,選取 [建立]

  6. 從工具列中,選取 [啟動但不偵錯] 啟動應用程式。 網頁瀏覽器預設會以位址 http://localhost:3000/ 開啟。 瀏覽器會保持開啟狀態,並針對每個儲存的變更重新轉譯。

  7. 建立其他資料夾與檔案,達成下列資料夾結構:

    ├─── public
    │   └─── index.html
    └───src
        ├─── components
        │   └─── PageLayout.jsx
        │   └─── ProfileData.jsx
        │   └─── SignInButton.jsx
        │   └─── SignOutButton.jsx
        └── App.css
        └── App.jsx
        └── authConfig.js
        └── graph.js
        └── index.css
        └── index.js
    

安裝身分識別和啟動套件

身分識別相關 npm 套件必須安裝在專案中,才能啟用使用者驗證。 針對專案樣式,將會使用 Bootstrap

  1. 在 [方案總管]中,以滑鼠右鍵按一下 [npm] 選項,然後選取 [安裝新的 npm 套件]
  2. 搜尋 @azure/MSAL-browser,然後選取 [安裝套件]。 針對 @azure/MSAL-react 重複。
  3. 搜尋並安裝 react-bootstrap
  4. 選取關閉

若要深入瞭解這些套件,請參閱 msal-browsermsal-react 中的文件。

建立驗證設定檔

  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",
            authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
            redirectUri: "http://localhost:3000",
        },
        cache: {
            cacheLocation: "sessionStorage", // This configures where your cache will be stored
            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: ["User.Read"]
    };
    
    /**
     * Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see:
     * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
     */
    export const graphConfig = {
        graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
    };
    
  2. 將下列值取代為來自 Microsoft Entra 系統管理中心的值。

    • clientId - 應用程式的識別碼,也稱為用戶端。 將 Enter_the_Application_Id_Here 取代為先前從已註冊應用程式 [概觀] 頁面記錄的 [應用程式 (用戶端) 識別碼]
    • authority - 這是由兩個部分組成:
      • 執行個體是雲端提供者的端點。 在國家雲端中檢查不同的可用端點。
      • 租用戶識別碼是註冊應用程式的租用戶識別碼。 將 Enter_the_Tenant_Info_Here 取代為先前從註冊應用程式的概觀頁面記錄的目錄 (租用戶) 識別碼值。
  3. 儲存檔案。

修改 index.js 以包含驗證提供者

需要驗證之應用程式的所有部分都必須包裝在 MsalProvider 元件中。 您會具現化 PublicClientApplication 然後將它傳遞至 MsalProvider

  1. 在 [src] 資料夾中,開啟 index.js,並以下列程式碼片段取代檔案的內容,以使用 msal 套件和啟動程式樣式:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    
    import { PublicClientApplication } from '@azure/msal-browser';
    import { MsalProvider } from '@azure/msal-react';
    import { msalConfig } from './authConfig';
    
    // Bootstrap components
    import 'bootstrap/dist/css/bootstrap.min.css';
    
    const msalInstance = new PublicClientApplication(msalConfig);
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    
    /**
     * We recommend wrapping most or all of your components in the MsalProvider component. It's best to render the MsalProvider as close to the root as possible.
     */
     root.render(
      <React.StrictMode>
          <MsalProvider instance={msalInstance}>
              <App />
          </MsalProvider>
      </React.StrictMode>
    );
    
  2. 儲存檔案。

下一步