Tutorial:在 Node.js 和 Express web 应用中让用户登录Tutorial: Sign-in users in a Node.js & Express web app

在本教程中,你将构建一个登录用户的 Web 应用。In this tutorial, you build a web app that signs-in users. 构建的 Web 应用使用适用于 Node.js 的 Microsoft 身份验证库 (MSAL)The web app you build uses the Microsoft Authentication Library (MSAL) for Node.

请按照本教程中的步骤进行操作:Follow the steps in this tutorial to:

  • 在 Azure 门户中注册应用程序Register the application in the Azure portal
  • 创建 Express web 应用项目Create an Express web app project
  • 安装身份验证库包Install the authentication library packages
  • 添加应用注册详细信息Add app registration details
  • 为用户登录添加代码Add code for user login
  • 测试应用程序Test the app

先决条件Prerequisites

注册应用程序Register the application

首先,请完成向 Microsoft 标识平台注册应用程序中的步骤来注册你的应用。First, complete the steps in Register an application with the Microsoft identity platform to register your app.

对于应用注册,请使用以下设置:Use the following settings for your app registration:

  • 名称:ExpressWebApp(建议)Name: ExpressWebApp (suggested)
  • 支持的帐户类型:任何组织目录(任何 Azure AD 目录 - 多租户)中的帐户Supported account types: Accounts in any organizational directory (Any Azure AD directory - Multitenant)
  • 平台类型:WebPlatform type: Web
  • 重定向 URI:http://localhost:3000/redirectRedirect URI: http://localhost:3000/redirect
  • 客户端机密:*********(记录此值以便在后面的步骤中使用 - 它只显示一次)Client secret: ********* (record this value for use in a later step - it's shown only once)

创建项目Create the project

创建文件夹来承载你的应用程序,例如 ExpressWebApp。Create a folder to host your application, for example ExpressWebApp.

  1. 首先,在终端中更改到你的项目目录,然后运行以下 npm 命令:First, change to your project directory in your terminal and then run the following npm commands:
    npm init -y
    npm install --save express
  1. 接下来,创建名为 index.js 的文件并添加以下代码:Next, create file named index.js and add the following code:
    const express = require("express");
    const msal = require('@azure/msal-node');
    
    const SERVER_PORT = process.env.PORT || 3000;
    
    // Create Express App and Routes
    const app = express();

    app.listen(SERVER_PORT, () => console.log(`Msal Node Auth Code Sample app listening on port ${SERVER_PORT}!`))

现在,在端口 3000 上运行了一个简单的 Web 服务器。You now have a simple web server running on port 3000. 项目的文件和文件夹结构应类似于下面这样:The file and folder structure of your project should look similar to the following:

ExpressWebApp/
├── index.js
└── package.json

安装身份验证库Install the auth library

在终端中找到项目目录的根,并通过 NPM 安装 MSAL 节点包。Locate the root of your project directory in a terminal and install the MSAL Node package via NPM.

    npm install --save @azure/msal-node

添加应用注册详细信息Add app registration details

在之前创建的 index.js 文件中,添加以下代码:In the index.js file you've created earlier, add the following code:

    // Before running the sample, you will need to replace the values in the config, 
    // including the clientSecret
    const config = {
        auth: {
            clientId: "Enter_the_Application_Id",
            authority: "Enter_the_Cloud_Instance_Id_Here/Enter_the_Tenant_Id_here",
            clientSecret: "Enter_the_Client_secret"
        },
        system: {
            loggerOptions: {
                loggerCallback(loglevel, message, containsPii) {
                    console.log(message);
                },
                piiLoggingEnabled: false,
                logLevel: msal.LogLevel.Verbose,
            }
        }
    };

使用从 Azure 应用注册门户获取的值填写以下详细信息:Fill in these details with the values you obtain from Azure app registration portal:

  • Enter_the_Tenant_Id_here 应是以下各项之一:Enter_the_Tenant_Id_here should be one of the following:
    • 如果应用程序支持“此组织目录中的帐户”,请将此值替换为“租户 ID”或“租户名称”。If your application supports accounts in this organizational directory, replace this value with the Tenant ID or Tenant name. 例如,contoso.microsoft.comFor example, contoso.microsoft.com.
    • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为“organizations”。If your application supports accounts in any organizational directory, replace this value with organizations.
  • Enter_the_Application_Id_Here:已注册应用程序的应用程序(客户端)ID。Enter_the_Application_Id_Here: The Application (client) ID of the application you registered.
  • Enter_the_Cloud_Instance_Id_Here:在其中注册应用程序的 Azure 云实例。Enter_the_Cloud_Instance_Id_Here: The Azure cloud instance in which your application is registered.
    • 对于国家/地区云(例如中国云),可以在国家/地区云中找到相应值。For national clouds (for example, China), you can find appropriate values in National clouds.
  • Enter_the_Client_secret:将此值替换为先前创建的客户端机密。Enter_the_Client_secret: Replace this value with the client secret you created earlier. 若要生成新密钥,请在 Azure 门户的应用注册设置中使用“证书和密码”。To generate a new key, use Certificates & secrets in the app registration settings in the Azure portal.

警告

源代码中的任何纯文本机密都会增加安全风险。Any plaintext secret in source code poses an increased security risk. 本文使用纯文本客户端机密只是为了简单起见。This article uses a plaintext client secret for simplicity only. 在机密客户端应用程序中使用证书凭据(而不是客户端机密),尤其是计划部署到生产环境的应用。Use certificate credentials instead of client secrets in your confidential client applications, especially those apps you intend to deploy to production.

为用户登录添加代码Add code for user login

在之前创建的 index.js 文件中,添加以下代码:In the index.js file you've created earlier, add the following code:

    // Create msal application object
    const cca = new msal.ConfidentialClientApplication(config);
    
    app.get('/', (req, res) => {
        const authCodeUrlParameters = {
            scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"],
            redirectUri: "http://localhost:3000/redirect",
        };
    
        // get url to sign user in and consent to scopes needed for application
        cca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
            res.redirect(response);
        }).catch((error) => console.log(JSON.stringify(error)));
    });
    
    app.get('/redirect', (req, res) => {
        const tokenRequest = {
            code: req.query.code,
            scopes: ["https://microsoftgraph.chinacloudapi.cn/user.read"],
            redirectUri: "http://localhost:3000/redirect",
        };
    
        cca.acquireTokenByCode(tokenRequest).then((response) => {
            console.log("\nResponse: \n:", response);
            res.sendStatus(200);
        }).catch((error) => {
            console.log(error);
            res.status(500).send(error);
        });
    });

测试登录Test sign in

你已完成应用程序的创建,现在即可测试应用的功能。You've completed creation of the application and are now ready to test the app's functionality.

  1. 从项目文件夹的根目录中运行以下命令,启动 Node.js 控制台应用:Start the Node.js console app by running the following command from within the root of your project folder:
   node index.js
  1. 打开浏览器窗口并导航到 http://localhost:3000Open a browser window and navigate to http://localhost:3000. 应该会出现登录屏幕:You should see a sign-in screen:

显示 Azure AD 登录屏幕

  1. 输入凭据后,你应该会看到一个同意屏幕,要求你批准应用的权限。Once you enter your credentials, you should see a consent screen asking you to approve the permissions for the app.

显示 Azure AD 许可屏幕

应用程序的工作原理How the application works

在本教程中,通过将 MSAL Node ConfidentialClientApplication 对象的配置对象传递给它,将其初始化 (MsalConfig),其中包含 Azure 门户上 Azure AD 应用注册获得的参数。In this tutorial, you initialized an MSAL Node ConfidentialClientApplication object by passing it a configuration object (msalConfig) that contains parameters obtained from your Azure AD app registration on Azure portal. 你创建的 Web 应用使用 OAuth 2.0 授权代码授予流来登录用户并获取 ID 和访问令牌。The web app you created uses the OAuth 2.0 Authorization code grant flow to sign-in users and obtain ID and access tokens.

后续步骤Next steps

如果你想要更深入了解 Microsoft 标识平台上的 Node.js & Express web 应用程序开发,请参阅由多部分组成的方案系列:If you'd like to dive deeper into Node.js & Express web application development on the Microsoft identity platform, see our multi-part scenario series: