教學課程:準備 JavaScript 單頁應用程式以進行驗證
適用於:綠色圓圈加上白色複選標記符號 Workforce 租戶
外部租戶(了解更多)
在本教學課程中,您將建置 JavaScript 單頁應用程式 (SPA),並使用 Microsoft 身分識別平台來準備驗證。 本教學課程示範如何使用 npm
建立 JavaScript SPA、建立驗證和授權所需的檔案,並將租使用者詳細數據新增至原始程式碼。 應用程式可以用於工作用租戶中的員工,或使用外部租戶的客戶使用。
在本教學課程中,您將:
- 建立新的 JavaScript 專案
- 安裝驗證所需的套件
- 建立檔案結構,並將程式代碼新增至伺服器檔案
- 將租使用者詳細數據新增至驗證組態檔
先決條件
- Node.js。
- Visual Studio Code 或其他程式碼編輯工具。
建立 JavaScript 專案並安裝相依性
開啟 Visual Studio Code,選取 [檔案]>[開啟資料夾...]。流覽至 並選取要在其中建立專案的位置。
選取 [終端機]>[新增終端機]來開啟新的終端機。
執行下列命令以建立新的 JavaScript 專案:
npm init -y
建立其他資料夾和檔案,以達成下列項目結構:
└── public └── authConfig.js └── auth.js └── claimUtils.js └── index.html └── signout.html └── styles.css └── ui.js └── server.js └── package.json
在 終端機中,執行下列命令以安裝專案所需的相依性:
npm install express morgan @azure/msal-browser
將程式代碼新增至伺服器檔案
Express 是適用於 Node.js的 Web 應用程式架構。 它用來建立裝載應用程式的伺服器。 Morgan 是將 HTTP 要求記錄至主控台的中間件。 伺服器檔案可用來裝載這些相依性,並包含應用程式的路由。 驗證和授權是由適用於 JavaScript 的 Microsoft 驗證連結庫 (MSAL.js)處理。
將下列程式代碼新增至 server.js 檔案:
const express = require('express'); const morgan = require('morgan'); const path = require('path'); const DEFAULT_PORT = process.env.PORT || 3000; // initialize express. const app = express(); // Configure morgan module to log all requests. app.use(morgan('dev')); // serve public assets. app.use(express.static('public')); // serve msal-browser module app.use(express.static(path.join(__dirname, "node_modules/@azure/msal-browser/lib"))); // set up a route for signout.html app.get('/signout', (req, res) => { res.sendFile(path.join(__dirname + '/public/signout.html')); }); // set up a route for redirect.html app.get('/redirect', (req, res) => { res.sendFile(path.join(__dirname + '/public/redirect.html')); }); // set up a route for index.html app.get('/', (req, res) => { res.sendFile(path.join(__dirname + '/index.html')); }); app.listen(DEFAULT_PORT, () => { console.log(`Sample app listening on port ${DEFAULT_PORT}!`); }); module.exports = app;
在此程式代碼中,應用程式 變數被初始化為使用 Express 模組來提供公用資產。 MSAL 瀏覽器 可作為靜態資產,並用來起始驗證流程。
將租使用者詳細數據新增至 MSAL 設定
authConfig.js 檔案包含驗證流程的組態設定,並用來使用必要的驗證設定來設定 MSAL.js。
開啟 公用/authConfig.js,並新增下列程式代碼:
/** * 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 */ const msalConfig = { auth: { // WORKFORCE TENANT authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Replace the placeholder with your tenant info redirectUri: '/', // You must register this URI on App Registration. Defaults to window.location.href e.g. http://localhost:3000/ navigateToLoginRequestUrl: true, // 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. storeAuthStateInCookie: false, // set this to true if you have to support IE }, system: { loggerOptions: { loggerCallback: (level, message, containsPii) => { if (containsPii) { return; } switch (level) { case msal.LogLevel.Error: console.error(message); return; case msal.LogLevel.Info: console.info(message); return; case msal.LogLevel.Verbose: console.debug(message); return; case msal.LogLevel.Warning: console.warn(message); 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://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#openid-connect-scopes */ const loginRequest = { scopes: ["User.Read"], }; /** * An optional silentRequest object can be used to achieve silent SSO * between applications by providing a "login_hint" property. */ // const silentRequest = { // scopes: ["openid", "profile"], // loginHint: "example@domain.net" // }; // exporting config object for jest if (typeof exports !== 'undefined') { module.exports = { msalConfig: msalConfig, loginRequest: loginRequest, }; module.exports = { msalConfig: msalConfig, loginRequest: loginRequest, }; }
將下列值取代為來自 Microsoft Entra 系統管理中心的值:
- 尋找
Enter_the_Application_Id_Here
值,然後用在 Microsoft Entra 系統管理中心註冊的應用程式的 應用程式識別碼(clientId) 取代它。 - 尋找
Enter_the_Tenant_Info_Here
值,並將它取代為您在 Microsoft Entra 系統管理中心中建立的工作力租戶 的租戶識別碼。
- 尋找
儲存檔案。