快速入门:使用应用的标识获取令牌并从 Node.js 控制台应用中调用 Microsoft Graph APIQuickstart: Acquire a token and call Microsoft Graph API from a Node.js console app using app's identity

在本快速入门中,你将下载并运行一个代码示例,该示例演示 Node.js 控制台应用程序如何使用应用的标识获取访问令牌来调用 Microsoft Graph API 并在目录中显示用户列表In this quickstart, you download and run a code sample that demonstrates how a Node.js console application can get an access token using the app's identity to call the Microsoft Graph API and display a list of users in the directory. 代码示例演示无人参与的作业或 Windows 服务如何使用应用程序标识而不是用户标识运行。The code sample demonstrates how an unattended job or Windows service can run with an application identity, instead of a user's identity.

本快速入门通过客户端凭据授权使用适用于 Node.js 的 Microsoft 身份验证库 (MSAL Node)This quickstart uses the Microsoft Authentication Library for Node.js (MSAL Node) with the client credentials grant.

先决条件Prerequisites

注册并下载快速入门应用程序Register and download your quickstart application

请按照以下步骤开始使用。Follow the steps below to get started.

步骤 1:注册应用程序Step 1: Register your application

若要手动注册应用程序并将应用的注册信息添加到解决方案,请执行以下步骤:To register your application and add the app's registration information to your solution manually, follow these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 如果有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器 ,选择要在其中注册应用程序的租户。
  3. 搜索并选择“Azure Active Directory” 。Search for and select Azure Active Directory.
  4. 在“管理”下,选择“应用注册” > “新建注册” 。Under Manage, select App registrations > New registration.
  5. 输入应用程序的名称(例如 msal-node-cli)。Enter a Name for your application, for example msal-node-cli. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
  6. 选择“注册” 。Select Register.
  7. 在“管理”下,选择“证书和机密”。 Under Manage, select Certificates & secrets.
  8. 在“客户端机密”下,选择“新建客户端机密”,输入名称,然后选择“添加” 。Under Client secrets, select New client secret, enter a name, and then select Add. 将机密值记录在安全的位置,以供在后面的步骤中使用。Record the secret value in a safe location for use in a later step.
  9. 在“管理”下,选择“API 权限” > “添加权限” 。Under Manage, select API Permissions > Add a permission. 选择“Microsoft Graph”。Select Microsoft Graph.
  10. 选择“应用程序权限”。Select Application permissions.
  11. 在“用户”节点下选择“User.Read.All”,然后选择“添加权限” 。Under User node, select User.Read.All, then select Add permissions.

下载并配置快速入门应用Download and configure your quickstart app

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in Azure portal

为使本快速入门的代码示例正常运行,需创建客户端机密,并添加 Graph API 的 User.Read.All 应用程序权限。For the code sample for this quickstart to work, you need to create a client secret, and add Graph API's User.Read.All application permission.

已配置 应用程序已使用这些属性进行配置。Already configured Your application is configured with these attributes.

步骤 2:下载 Node.js 项目Step 2: Download your Node.js project

备注

Enter_the_Supported_Account_Info_Here

步骤 3:配置 Node.js 项目Step 3: Configure your Node.js project

  1. 将 zip 文件提取到靠近磁盘根目录的本地文件夹,例如 C:/Azure-Samples。Extract the zip file to a local folder close to the root of the disk, for example, C:/Azure-Samples.

  2. 编辑 .env,将字段 TENANT_IDCLIENT_IDCLIENT_SECRET 的值替换为以下代码片段:Edit .env and replace the values of the fields TENANT_ID, CLIENT_ID, and CLIENT_SECRET with the following snippet:

    "TENANT_ID": "Enter_the_Tenant_Id_Here",
    "CLIENT_ID": "Enter_the_Application_Id_Here",
    "CLIENT_SECRET": "Enter_the_Client_Secret_Here"
    

    其中:Where:

    • Enter_the_Application_Id_Here - 先前注册的应用程序的应用程序(客户端)ID。Enter_the_Application_Id_Here - is the Application (client) ID of the application you registered earlier. 在 Azure 门户的应用注册“概述”窗格中找到此 ID。Find this ID on the app registration's Overview pane in the Azure portal.
    • Enter_the_Tenant_Id_Here - 将此值替换为租户 ID 或租户名称(例如 contoso.microsoft.com) 。Enter_the_Tenant_Id_Here - replace this value with the Tenant ID or Tenant name (for example, contoso.microsoft.com). 在 Azure 门户的应用注册“概述”窗格中找到这些值。Find these values on the app registration's Overview pane in the Azure portal.
    • Enter_the_Client_Secret_Here - 将此值替换为先前创建的客户端密码。Enter_the_Client_Secret_Here - 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.

如果尝试在此时运行应用程序,则会收到“HTTP 403 - 禁止访问”错误:Insufficient privileges to complete the operationIf you try to run the application at this point, you'll receive HTTP 403 - Forbidden error: Insufficient privileges to complete the operation. 之所以出现这种错误,是因为任何仅限应用的权限都需要管理员同意:目录的全局管理员必须为应用程序授予同意。This error happens because any app-only permission requires admin consent: a global administrator of your directory must give consent to your application. 根据自己的角色选择下面的一个选项:Select one of the options below depending on your role:

全局租户管理员Global tenant administrator

如果你是全局租户管理员,请转到 Azure 门户的“应用程序注册”中的“API 权限”页,选择“为 {租户名称} 授予管理员同意”(其中,{租户名称} 是目录的名称) 。If you are a global tenant administrator, go to API Permissions page in the Azure portal's Application Registration and select Grant admin consent for {Tenant Name} (where {Tenant Name} is the name of your directory).

如果你是全局管理员,请转到“API 权限”页,选择“为 Enter_the_Tenant_Name_Here 授予管理员许可”If you are a global administrator, go to API Permissions page select Grant admin consent for Enter_the_Tenant_Name_Here

标准用户Standard user

如果你是租户的标准用户,则需请求全局管理员为你的应用程序授予管理员同意。If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. 为此,请将以下 URL 提供给管理员:To do this, give the following URL to your administrator:

https://login.partner.microsoftonline.cn/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here

其中:Where:

  • Enter_the_Tenant_Id_Here - 将此值替换为 租户 ID租户名称(例如 contoso.microsoft.com)Enter_the_Tenant_Id_Here - replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com)
  • Enter_the_Application_Id_Here - 是已注册应用程序的 应用程序(客户端)IDEnter_the_Application_Id_Here - is the Application (client) ID for the application you registered.

步骤 4:运行应用程序Step 4: Run the application

步骤 5:运行应用程序Step 5: Run the application

定位到命令提示符或控制台中示例的根文件夹(package.json 所在位置)。Locate the sample's root folder (where package.json resides) in a command prompt or console. 需要安装一次此示例的依赖项:You'll need to install the dependencies of this sample once:

npm install

然后,通过命令提示符或控制台运行应用程序:Then, run the application via command prompt or console:

node . --op getUsers

应该会在控制台输出上看到一些 JSON 片段,表示 Azure AD 目录中的用户列表。You should see on the console output some JSON fragment representing a list of users in your Azure AD directory.

关于代码About the code

下面讨论了示例应用程序的一些重要方面。Below, some of the important aspects of the sample application are discussed.

MSAL NodeMSAL Node

MSAL Node 是一个用于登录用户和请求令牌的库,此类令牌用于访问受 Microsoft 标识平台保护的 API。MSAL Node is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. 如前所述,本快速入门通过应用程序权限请求令牌(使用应用程序自身的标识),而不是通过委托的权限。As described, this quickstart requests tokens by application permissions (using the application's own identity) instead of delegated permissions. 此示例中使用的身份验证流称为 OAuth 2.0 客户端凭据流The authentication flow used in this case is known as OAuth 2.0 client credentials flow. 若要详细了解如何搭配使用 MSAL Node 和守护程序应用,请参阅方案:守护程序应用程序For more information on how to use MSAL Node with daemon apps, see Scenario: Daemon application.

可通过运行以下 npm 命令安装 MSAL Node。You can install MSAL Node by running the following npm command.

npm install @azure/msal-node --save

MSAL 初始化MSAL initialization

可以通过添加以下代码,为 MSAL 添加引用:You can add the reference for MSAL by adding the following code:

const msal = require('@azure/msal-node');

然后,使用以下代码对 MSAL 进行初始化:Then, initialize MSAL using the following code:

const msalConfig = {
    auth: {
        clientId: "Enter_the_Application_Id_Here",
        authority: "https://login.partner.microsoftonline.cn/Enter_the_Tenant_Id_Here",
        clientSecret: "Enter_the_Client_Secret_Here",
   } 
};
const cca = new msal.ConfidentialClientApplication(msalConfig);
其中:Where: 说明Description
clientId 是在 Azure 门户中注册的应用程序的 应用程序(客户端) IDIs the Application (client) ID for the application registered in the Azure portal. 可以在 Azure 门户的应用的“概览”页中找到此值。You can find this value in the app's Overview page in the Azure portal.
authority 用户要进行身份验证的 STS 终结点。The STS endpoint for user to authenticate. 对于公有云,通常为 https://login.partner.microsoftonline.cn/{tenant},其中 {tenant} 是租户名称或租户 ID。Usually https://login.partner.microsoftonline.cn/{tenant} for public cloud, where {tenant} is the name of your tenant or your tenant Id.
clientSecret 是在 Azure 门户中为应用程序创建的客户端机密。Is the client secret created for the application in Azure Portal.

有关详细信息,请参阅 ConfidentialClientApplication 的参考文档For more information, please see the reference documentation for ConfidentialClientApplication

请求令牌Requesting tokens

若要通过应用的标识来请求令牌,请使用 acquireTokenByClientCredential 方法:To request a token using app's identity, use acquireTokenByClientCredential method:

const tokenRequest = {
    scopes: [ 'https://microsoftgraph.chinacloudapi.cn/.default' ],
};

const tokenResponse = await cca.acquireTokenByClientCredential(tokenRequest);
其中:Where: 说明Description
tokenRequest 包含请求的范围。Contains the scopes requested. 对于机密客户端,这应该使用与 {Application ID URI}/.default 类似的格式,指示所请求的范围是在 Azure 门户的应用对象集中静态定义的范围(就 Microsoft Graph 来说,{Application ID URI} 指向 https://microsoftgraph.chinacloudapi.cn)。For confidential clients, this should use the format similar to {Application ID URI}/.default to indicate that the scopes being requested are the ones statically defined in the app object set in the Azure Portal (for Microsoft Graph, {Application ID URI} points to https://microsoftgraph.chinacloudapi.cn). 对于自定义 Web API,{Application ID URI} 在 Azure 门户的“应用程序注册”的“公开 API”部分中定义。For custom web APIs, {Application ID URI} is defined under Expose an API section in Azure Portal's Application Registration.
tokenResponse 响应包含所请求范围的访问令牌。The response contains an access token for the scopes requested.

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.

后续步骤Next steps

若要详细了解如何通过 MSAL Node 进行守护程序/控制台应用开发,请参阅教程:To learn more about daemon/console app development with MSAL Node, see the tutorial: