教程:从桌面应用使用 Azure Active Directory B2C 授予对 Node.js Web API 的访问权限Tutorial: Grant access to a Node.js web API from a desktop app using Azure Active Directory B2C

本教程展示了如何从 Windows Presentation Foundation (WPF) 桌面应用(也受 Azure AD B2C 保护)调用受 Azure Active Directory B2C (Azure AD B2C) 保护的 Node.js Web API。This tutorial shows you how to call a Node.js web API protected by Azure Active Directory B2C (Azure AD B2C) from a Windows Presentation Foundation (WPF) desktop app, also protected by Azure AD B2C.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 添加 Web API 应用程序Add a web API application
  • 配置 Web API 的范围Configure scopes for a web API
  • 授予 Web API 权限Grant permissions to the web API
  • 将示例更新为使用该应用程序Update the sample to use the application

先决条件Prerequisites

完成教程:在本机桌面客户端中对用户进行身份验证Complete the steps and prerequisites in Tutorial: Authenticate users in a native desktop client.

添加 Web API 应用程序Add a web API application

Web API 资源需要先在租户中注册,然后才能接受并响应通过提供访问令牌的客户端应用程序所提出的受保护资源请求。Web API resources need to be registered in your tenant before they can accept and respond to protected resource requests by client applications that present an access token.

要在 Azure AD B2C 租户中注册应用程序,可以使用新的统一“应用注册”体验或旧版“应用程序(旧版)”体验 。To register an application in your Azure AD B2C tenant, you can use our new unified App registrations experience or our legacy Applications (Legacy) experience. 详细了解此新体验Learn more about the new experience.

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 在顶部菜单中选择“目录 + 订阅”筛选器,然后选择包含Azure AD B2C 租户的目录。Select the Directory + subscription filter in the top menu, and then select the directory that contains your Azure AD B2C tenant.
  3. 在左侧菜单中,选择“Azure AD B2C”。In the left menu, select Azure AD B2C. 或者,选择“所有服务”并搜索并选择“Azure AD B2C”。Or, select All services and search for and select Azure AD B2C.
  4. 选择“应用注册”,然后选择“新建注册” 。Select App registrations, and then select New registration.
  5. 输入应用程序的“名称”。Enter a Name for the application. 例如,“webapi1”。For example, webapi1.
  6. 在“重定向 URI”下选择“Web”,然后输入 Azure AD B2C 会将应用程序请求的任何令牌返回到其中的终结点。Under Redirect URI, select Web, and then enter an endpoint where Azure AD B2C should return any tokens that your application requests. 本教程中的示例在本地运行并在 http://localhost:5000 上进行侦听。In this tutorial, the sample runs locally and listens at http://localhost:5000.
  7. 选择“注册”。Select Register.
  8. 记录“应用程序(客户端) ID”,以便在后续步骤中使用。Record the Application (client) ID for use in a later step.

接下来,启用隐式授权流:Next, enable the implicit grant flow:

  1. 在“管理”下,选择“身份验证”。 Under Manage, select Authentication.
  2. 选择“尝试新体验”(如果已显示)。Select Try out the new experience (if shown).
  3. 在“隐式授权”下,选中“访问令牌”和“ID 令牌”复选框 。Under Implicit grant, select both the Access tokens and ID tokens check boxes.
  4. 选择“保存”。Select Save.

配置范围Configure scopes

可通过范围控制对受保护资源的访问。Scopes provide a way to govern access to protected resources. Web API 使用作用域实施基于作用域的访问控制。Scopes are used by the web API to implement scope-based access control. 例如,可以让某些用户拥有读取和写入访问权限,让另一些用户拥有只读权限。For example, some users could have both read and write access, whereas other users might have read-only permissions. 在本教程中,请为 Web API 定义读取和写入权限。In this tutorial, you define read and write permissions for the web API.

  1. 选择 “应用注册”Select App registrations.
  2. 选择“webapi1”应用程序以打开其“概览”页。Select the webapi1 application to open its Overview page.
  3. 在“管理”下,选择“公开 API” 。Under Manage, select Expose an API.
  4. 选择“应用程序 ID URI”旁边的“设置”链接。 Next to Application ID URI, select the Set link.
  5. 将默认值(一个 GUID)替换为 api,然后选择“保存”。Replace the default value (a GUID) with api, and then select Save. 完整的 URI 已显示,应采用 https://your-tenant-name.partner.onmschina.cn/api 格式。The full URI is shown, and should be in the format https://your-tenant-name.partner.onmschina.cn/api. Web 应用程序在请求 API 的访问令牌时,应将此 URI 添加为你为 API 定义的每个范围的前缀。When your web application requests an access token for the API, it should add this URI as the prefix for each scope that you define for the API.
  6. 在“此 API 定义的范围”下选择“添加范围”。 Under Scopes defined by this API, select Add a scope.
  7. 输入以下值来创建一个定义对 API 的读取访问权限的范围,然后选择“添加范围”:Enter the following values to create a scope that defines read access to the API, then select Add scope:
    1. 范围名称demo.readScope name: demo.read
    2. 管理员许可显示名称Read access to demo APIAdmin consent display name: Read access to demo API
    3. 管理员许可说明Allows read access to the demo APIAdmin consent description: Allows read access to the demo API
  8. 选择“添加范围”,输入以下值来添加一个定义对 API 的写入访问权限的范围,然后选择“添加范围”: Select Add a scope, enter the following values to add a scope that defines write access to the API, and then select Add scope:
    1. 范围名称demo.writeScope name: demo.write
    2. 管理员许可显示名称Write access to demo APIAdmin consent display name: Write access to demo API
    3. 管理员许可说明Allows write access to the demo APIAdmin consent description: Allows write access to the demo API

记下 demo.read 范围对应的“范围”下的值,以便在稍后的步骤中配置桌面应用程序时使用。Record the value under SCOPES for the demo.read scope to use in a later step when you configure the desktop application. 完整范围值类似于 https://contosob2c.partner.onmschina.cn/api/demo.readThe full scope value is similar to https://contosob2c.partner.onmschina.cn/api/demo.read.

授予权限Grant permissions

若要从本机客户端应用程序调用受保护的 Web API,需要向在 Azure AD B2C 中注册的 Web API 授予已注册的本机客户端应用程序权限。To call a protected web API from a native client application, you need to grant the registered native client application permissions to the web API you registered in Azure AD B2C.

在先决条件教程中,你注册了名为“nativeapp1”的本机客户端应用程序。In the prerequisite tutorial, you registered a native client application named nativeapp1. 以下步骤使用你向上述部分中“webapi1”公开的 API 范围来配置本机应用程序注册。The following steps configure that native application registration with the API scopes you exposed for webapi1 in the previous section. 这允许桌面应用程序从 Azure AD B2C 获取访问令牌,Web API 可以使用该令牌来验证和提供对其资源的作用域访问。This allows the desktop application to obtain an access token from Azure AD B2C that the web API can use to verify and provide scoped access to its resources. 在本教程的后面部分,你将配置并运行桌面应用程序和 Web API 代码示例。You configure and run both the desktop application and web API code samples later in the tutorial.

要在 Azure AD B2C 租户中注册应用程序,可以使用新的统一“应用注册”体验或旧版“应用程序(旧版)”体验 。To register an application in your Azure AD B2C tenant, you can use our new unified App registrations experience or our legacy Applications (Legacy) experience. 详细了解此新体验Learn more about the new experience.

  1. 选择“应用注册”,然后选择应该有权访问 API 的 本机客户端应用程序。Select App registrations, and then select the native client application that should have access to the API. 例如,“nativeapp1”。For example, nativeapp1.
  2. 在“管理”下选择“API 权限”。Under Manage, select API permissions.
  3. 在“已配置权限”下,选择“添加权限”。Under Configured permissions, select Add a permission.
  4. 选择“我的 API”选项卡。Select the My APIs tab.
  5. 选择应授予本机客户端应用程序访问权限的 API。Select the API to which the native client application should be granted access. 例如,“webapi1”。For example, webapi1.
  6. 在“权限”下展开“演示”,然后选择前面定义的范围。 Under Permission, expand demo, and then select the scopes that you defined earlier. 例如,demo.readdemo.writeFor example, demo.read and demo.write.
  7. 选择“添加权限”。Select Add permissions. 按照指示等待几分钟,然后继续下一步。As directed, wait a few minutes before proceeding to the next step.
  8. 选择“向(租户名称)授予管理员许可”。Select Grant admin consent for (your tenant name).
  9. 选择当前登录的管理员帐户,或者使用至少分配了“云应用程序管理员”角色的 Azure AD B2C 租户中的帐户登录。Select your currently signed-in administrator account, or sign in with an account in your Azure AD B2C tenant that's been assigned at least the Cloud application administrator role.
  10. 选择“接受”。Select Accept.
  11. 选择“刷新”,然后确认两个范围的“状态”下是否均显示“已授予...”。 Select Refresh, and then verify that "Granted for ..." appears under Status for both scopes. 传播权限可能需要几分钟时间。It might take a few minutes for the permissions to propagate.

用户通过 Azure AD B2C 进行身份验证,以使用 WPF 桌面应用程序。A user authenticates with Azure AD B2C to use the WPF desktop application. 桌面应用程序从 Azure AD B2C 获取授权,以访问受保护的 Web API。The desktop application obtains an authorization grant from Azure AD B2C to access the protected web API.

配置示例Configure the samples

现在已注册 Web API 并已配置范围和权限,请将桌面应用程序和 Web API 示例配置为使用 Azure AD B2C 租户。Now that the web API is registered and you have scopes and permissions configured, you configure the desktop application and web API samples to use your Azure AD B2C tenant.

更新桌面应用程序Update the desktop application

在本文的先决条件中,你修改了 WPF 桌面应用程序以便能够在 Azure AD B2C 租户中使用用户流进行登录。In a prerequisite for this article, you modified a WPF desktop application to enable sign-in with a user flow in your Azure AD B2C tenant. 在本部分中,将更新此同一应用程序以引用之前注册的 Web API,即“webapi1”。In this section, you update that same application to reference the web API you registered earlier, webapi1.

  1. 在 Visual Studio 中打开“active-directory-b2c-wpf”解决方案 (active-directory-b2c-wpf.sln)。Open the active-directory-b2c-wpf solution (active-directory-b2c-wpf.sln) in Visual Studio.

  2. 在“active-directory-b2c-wpf”项目中,打开“App.xaml.cs”文件并查找以下变量定义。In the active-directory-b2c-wpf project, open the App.xaml.cs file and find the following variable definitions.

    1. ApiScopes 变量的值替换为之前你在定义 demo.read 范围时记录的值。Replace the value of the ApiScopes variable with the value you recorded earlier when you defined the demo.read scope.
    2. ApiEndpoint 变量的值替换为之前在你的租户中注册 Web API(例如 webapi1)时记录的“重定向 URI”。Replace the value of the ApiEndpoint variable with the Redirect URI you recorded earlier when you registered the web API (for example, webapi1) in your tenant.

    下面是一个示例:Here's an example:

    public static string[] ApiScopes = { "https://contosob2c.partner.onmschina.cn/api/demo.read" };
    public static string ApiEndpoint = "http://localhost:5000";
    

获取和更新 Node.js API 示例Get and update the Node.js API sample

接下来,从 GitHub 获取 Node.js Web API 代码示例,并将其配置为使用你在 Azure AD B2C 租户中注册的 Web API。Next, get the Node.js web API code sample from GitHub and configure it to use the web API you registered in your Azure AD B2C tenant.

从 GitHub 下载 zip 文件或克隆示例 Web 应用。Download a zip file or clone the sample web app from GitHub.

git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi.git

该 Node.js Web API 示例使用 Passport.js 库来使得 Azure AD B2C 能够保护对 API 的调用。The Node.js web API sample uses the Passport.js library to enable Azure AD B2C to protect calls to the API.

  1. 打开 index.js 文件。Open the index.js file.

  2. 使用以下值更新这些变量定义。Update these variable definitions with the following values. <web-API-application-ID> 更改为之前注册的 Web API (webapi1) 的“应用程序(客户端) ID”。Change <web-API-application-ID> to the Application (client) ID of the web API you registered earlier (webapi1). <your-b2c-tenant> 更改为 Azure AD B2C 租户的名称。Change <your-b2c-tenant> to the name of your Azure AD B2C tenant.

    var clientID = "<web-API-application-ID>";
    var b2cDomainHost = "<your-b2c-tenant>.b2clogin.cn";
    var tenantIdGuid = "<your-b2c-tenant>.partner.onmschina.cn";
    var policyName = "B2C_1_signupsignin1";
    
  3. 由于你是在本地运行 API,因此请将 GET 方法的路由中的路径更新为 / 而不是 /hello 的演示应用位置:Since you're running the API locally, update the path in the route for the GET method to / instead of the demo app's location of /hello:

    app.get("/",
    

运行示例Run the samples

运行 Node.js Web APIRun the Node.js web API

  1. 启动 Node.js 命令提示符。Launch a Node.js command prompt.
  2. 切换到包含 Node.js 示例的目录。Change to the directory containing the Node.js sample. 例如 cd c:\active-directory-b2c-javascript-nodejs-webapiFor example cd c:\active-directory-b2c-javascript-nodejs-webapi
  3. 运行以下命令:Run the following commands:
    npm install && npm update
    
    node index.js
    

运行桌面应用程序Run the desktop application

  1. 在 Visual Studio 中打开 active-directory-b2c-wpf 解决方案。Open the active-directory-b2c-wpf solution in Visual Studio.
  2. F5 来运行桌面应用。Press F5 to run the desktop app.
  3. 使用在桌面应用中使用 Azure Active Directory B2C 对用户进行身份验证教程中使用的电子邮件地址和密码进行登录。Sign in using the email address and password used in Authenticate users with Azure Active Directory B2C in a desktop app tutorial.
  4. 选择“调用 API”按钮。Select the Call API button.

桌面应用程序向本地运行的 Web API 发出请求,并在验证有效的访问令牌时显示已登录用户的显示名称。The desktop application makes a request to the locally running web API, and upon verification of a valid access token, shows the signed-in user's display name.

显示名称将显示在 WPF 桌面应用程序的顶部窗格中

你的桌面应用程序(受 Azure AD B2C 保护)将调用本地运行的 Web API,其中此 API 也受 Azure AD B2C 保护。Your desktop application, protected by Azure AD B2C, is calling the locally running web API that is also protected by Azure AD B2C.

后续步骤Next steps

在本教程中,你了解了如何执行以下操作:In this tutorial, you learned how to:

  • 添加 Web API 应用程序Add a web API application
  • 配置 Web API 的范围Configure scopes for a web API
  • 授予 Web API 权限Grant permissions to the web API
  • 将示例更新为使用该应用程序Update the sample to use the application