共用方式為


教學課程:在外部租用戶中建立 Vanilla JavaScript SPA 以進行驗證

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

本教學課程內容;

  • 在 Visual Studio Code 中建立 Vanilla JavaScript 專案
  • 安裝必要的套件
  • 將程式碼新增至 server.js 以建立伺服器

必要條件

建立新的 Vanilla JavaScript 專案並安裝相依性

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

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

  3. 執行下列命令以建立新的 Vanilla JavaScript 專案:

    npm init -y
    
  4. 建立其他資料夾與檔案,達成下列專案結構:

        └── public
            └── authConfig.js
            └── authPopup.js
            └── authRedirect.js
            └── claimUtils.js
            └── index.html
            └── signout.html
            └── styles.css
            └── ui.js    
        └── server.js
    

安裝應用程式相依性

  1. 終端機中,執行下列命令以安裝專案所需的相依性:

    npm install express morgan @azure/msal-browser
    

編輯 server.js 檔案

快速是適用於 Node.js 的 Web 應用程式架構。 它用來建立裝載應用程式的伺服器。 Morgan 是將 HTTP 要求記錄至主控台的中介軟體。 伺服器檔案可用來裝載這些相依性,並包含應用程式的路由。 驗證和授權是由適用於 JavaScript 的 Microsoft 驗證程式庫 (MSAL.js) 處理。

  1. 將下列程式碼片段新增至 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}!`);
    });
    
    

在此程式碼中,應用程式變數會使用快速模組初始化,並使用快速來提供公用資產。 MSAL 瀏覽器 可作為靜態資產,並用來起始驗證流程。

後續步驟