教學課程:建立 React 單頁應用程式並準備進行驗證
適用於:具有白色勾選標記的綠色圓圈 工作團隊租戶
外部租戶(深入瞭解)
在本教學課程中,您將建置 React 單頁應用程式 (SPA),並使用Microsoft身分識別平台進行驗證。 本教學課程示範如何使用 npm
建立 React SPA、建立驗證和授權所需的檔案,並將租使用者詳細數據新增至原始程式碼。 應用程式可供在工作租戶中的員工使用,或供使用外部租戶的客戶使用。
在本教學課程中,您將:
- 建立新的 React 專案
- 安裝驗證所需的套件
- 建立檔案結構,並將程式代碼新增至伺服器檔案
- 將租使用者詳細數據新增至驗證組態檔
先決條件
- Node.js。
- Visual Studio Code 或是其他的程式碼編輯器。
建立新的 React 專案
開啟 Visual Studio Code,選取 [檔案]>[開啟資料夾...]。流覽至 並選取要在其中建立專案的位置。
選取 [終端機]>[新增終端機]來開啟新的終端機。
執行下列命令,以建立名為 reactspalocal的新 React 專案,並變更為新的目錄並啟動 React 專案。 網頁瀏覽器預設會以位址
http://localhost:3000/
開啟。 瀏覽器保持開啟狀態,並在每次儲存變更後重新渲染。npx create-react-app reactspalocal cd reactspalocal npm start
建立其他資料夾和檔案,以達到下列資料夾結構:
├─── 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
安裝身分識別和啟動程式套件
您必須在專案中安裝與身分識別相關的 npm 套件 ,才能啟用用戶驗證。 在項目樣式中,將會使用 Bootstrap。
在 終端機 列中,選取 + 圖示以建立新的終端機。 另一個終端機視窗將會開啟,而前一個節點的終端機會繼續在背景中運行。
確定已選取正確的目錄(reactspalocal),然後在終端機中輸入下列命令,以安裝相關的
msal
和bootstrap
套件。npm install @azure/msal-browser @azure/msal-react npm install react-bootstrap bootstrap
將租使用者詳細數據新增至 MSAL 設定
authConfig.js 檔案包含驗證流程的組態設定,並用來使用必要的驗證設定來設定 MSAL.js。
在 [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" // };
將下列值取代為來自 Microsoft Entra 系統管理中心的值。
-
clientId
- 應用程式的識別碼,也稱為用戶端。 將Enter_the_Application_Id_Here
替換為先前從已註冊應用程式的概觀頁面記錄的 應用程式(用戶端)ID 的值。 -
authority
- 這由兩個部分組成:- 實例 是雲端提供者的端點。 請檢查 國家雲端中不同的可用端點。
- 租戶 ID 是應用程式註冊所在租用戶的識別碼。 將 Enter_the_Tenant_Info_Here 更換為早先在已註冊應用程式概觀頁面上記錄的 目錄(租戶)ID 值。
-
儲存檔案。
新增驗證提供者
msal
套件可用來在應用程式中提供驗證。
msal-browser
套件可用來處理驗證流程,而 msal-react
套件則用來整合 msal-browser
與 React。
addEventCallback
用來接聽驗證程式期間發生的事件,例如當使用者成功登入時。
setActiveAccount
方法可用來設定應用程式的使用中帳戶,用來判斷要顯示的用戶資訊。
在 [src] 資料夾中,開啟 index.js,並將檔案內容替換為下列代碼片段,以使用
msal
套件和 Bootstrap 樣式: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}/> );
儲存檔案。
若要深入瞭解這些套件,請參閱 msal-browser
和 msal-react
中的檔。
新增主要應用程式元件
需要驗證之應用程式的所有部分都必須包裝在 MsalProvider
元件中。 您可以設定 instance
變數,呼叫 useMsal
攔截以取得 PublicClientApplication
實體,然後將它傳遞至 MsalProvider
。
MsalProvider
元件會透過 React 的內容 API,在整個應用程式中提供 PublicClientApplication
實例。
MsalProvider
下的所有元件都可以透過上下文存取 PublicClientApplication
實例,以及 msal-react
提供的所有鉤子和元件。
在 [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;
儲存檔案。