教程:准备用于身份验证的 JavaScript 单页应用程序

在本教程中,你将生成一个 JavaScript 单页应用程序(SPA),并准备它以使用Microsoft标识平台进行身份验证。 本教程演示如何使用 npmJavaScript SPA 创建、创建身份验证和授权所需的文件,并将租户详细信息添加到源代码。 应用程序可用于工作人员租户中的员工。

在本教程中,你将:

  • 创建新的 JavaScript 项目
  • 安装身份验证所需的包
  • 创建文件结构并将代码添加到服务器文件
  • 将租户详细信息添加到身份验证配置文件

先决条件

创建 JavaScript 项目并安装依赖项

  1. 打开 Visual Studio Code,选择“ 文件>打开文件夹...”。导航到并选择要在其中创建项目的位置。

  2. 通过选择“终端”>“新终端”打开一个新的终端。

  3. 运行以下命令以创建新的 JavaScript 项目:

    npm init -y
    
  4. 创建额外的文件夹和文件,以实现以下项目结构:

    └── public
        └── authConfig.js
        └── auth.js
        └── claimUtils.js
        └── index.html
        └── signout.html
        └── styles.css
        └── ui.js    
    └── server.js
    └── package.json
    
  5. 在“终端”中,运行以下命令以安装项目所需的依赖项:

    npm install express morgan @azure/msal-browser
    

将代码添加到服务器文件

Express 是用于 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}!`);
    });
    
    module.exports = app;
    

在此代码中, app 变量被 express 模块初始化,该模块用于提供公共资产服务。 MSAL-browser 用作静态资产,用于启动身份验证流。

将租户详细信息添加到 MSAL 配置

authConfig.js 文件包含身份验证流的配置设置,用于使用所需的身份验证设置来配置 MSAL.js

  1. 打开 公共/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.partner.microsoftonline.cn/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://docs.azure.cn/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,
        };
    }
    
  2. 将以下值替换为来自 Microsoft Entra 管理中心的值:

    • 找到 Enter_the_Application_Id_Here 值并将其替换为在 Microsoft Entra 管理中心中注册的应用的应用程序 ID (clientId)
    • 找到 Enter_the_Tenant_Info_Here 值,并将其替换为在 Microsoft Entra 管理中心中创建的工作人员租户的“租户 ID”
  3. 保存文件。

后续步骤