快速入门:调用受 Microsoft 标识平台保护的 ASP.NET Web APIQuickstart: Call an ASP.NET web API protected by Microsoft identity platform

在本快速入门中,你将公开一个 Web API 并对其进行保护,以便只有经过身份验证的用户可以访问它。In this quickstart, you expose a Web API and protect it so that only authenticated user can access it. 本示例演示如何公开 ASP.NET Web API,使它可以接受与 Microsoft 标识平台集成的任何公司或组织中的工作和学校帐户颁发的令牌。This sample shows how to expose a ASP.NET Web API so it can accept tokens issued by work and school accounts from any company or organization that has integrated with Microsoft identity platform.

本示例还包含 Windows 桌面应用程序 (WPF) 客户端,该客户端演示了如何请求访问令牌以访问 Web API。The sample also includes a Windows Desktop application (WPF) client that demonstrates how you can request an access token to access a web API.

先决条件Prerequisites

若要运行本示例,需要满足以下先决条件:To run this sample, you will need the following:

下载或克隆本示例Download or clone this sample

可以从 shell 或命令行克隆本示例:You can clone this sample from your shell or command line:

git clone https://github.com/AzureADQuickStarts/AppModelv2-NativeClient-DotNet.git

或者,可以下载 ZIP 文件格式的示例Or, you can download the sample as a ZIP file.

在 Azure 门户中注册 Web APIRegister your Web API in the Azure portal

选择要在其中创建应用程序的 Azure AD 租户Choose the Azure AD tenant where you want to create your applications

若要手动注册应用,首先需要执行以下步骤:If you want to register your apps manually, as a first step you'll need to:

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal using a work or school account.
  2. 如果你的帐户存在于多个 Azure AD 租户中,请在页面顶部菜单的右上角选择你的个人资料,然后切换目录If your account is present in more than one Azure AD tenant, select your profile at the top-right corner in the menu on top of the page, and then switch directory. 将门户会话更改为所需的 Azure AD 租户。Change your portal session to the desired Azure AD tenant.

注册服务应用 (TodoListService)Register the service app (TodoListService)

  1. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.

  2. 选择“新注册”。 Select New registration.

  3. 出现“注册应用程序”页后,请输入应用程序的注册信息: When the Register an application page appears, enter your application's registration information:

    • 在“名称” 部分输入一个会显示给应用用户的有意义的应用程序名称,例如 AppModelv2-NativeClient-DotNet-TodoListServiceIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example AppModelv2-NativeClient-DotNet-TodoListService.
    • 将“支持的帐户类型”更改为“任何组织目录中的帐户”。 Change Supported account types to Accounts in any organizational directory.
    • 选择“注册” 以创建应用程序。Select Register to create the application.
  4. 在应用的“概述”页上,找到“应用程序(客户端) ID”值,并记下该值以供后续使用 。On the app Overview page, find the Application (client) ID value and record it for later. 稍后需要使用它为此项目配置 Visual Studio 配置文件(TodoListService\Web.config 中的 ClientId)。You'll need it to configure the Visual Studio configuration file for this project (ClientId in TodoListService\Web.config).

  5. 选择“公开 API”部分并执行以下操作: Select the Expose an API section, and:

    • 选择“添加范围” Select Add a scope
    • 选择“保存并继续”,接受建议的应用程序 ID URI (api://{clientId}) accept the proposed Application ID URI (api://{clientId}) by selecting Save and Continue
    • 输入以下参数:Enter the following parameters:
      • 对于“范围名称”,请使用 access_as_userfor Scope name use access_as_user
      • 确保为“谁能许可”选择了“管理员和用户”选项 。Ensure the Admins and users option is selected for Who can consent
      • 在“管理员许可显示名称”中键入 Access TodoListService as a userin Admin consent display name type Access TodoListService as a user
      • 在“管理员许可说明”中键入 Accesses the TodoListService web API as a userin Admin consent description type Accesses the TodoListService web API as a user
      • 在“用户许可显示名称”中键入 Access TodoListService as a userin User consent display name type Access TodoListService as a user
      • 在“用户许可说明”中键入 Accesses the TodoListService web API as a userin User consent description type Accesses the TodoListService web API as a user
      • 将“状态”保留为“已启用” Keep State as Enabled
      • 选择“添加范围” Select Add scope

配置服务项目以匹配注册的 Web APIConfigure the service project to match the registered web API

  1. 在 Visual Studio 中打开解决方案,然后打开 TodoListService 项目根目录下的 Web.config 文件。Open the solution in Visual Studio and then open the Web.config file under the root of TodoListService project.
  2. ida:ClientId 参数的值替换为刚刚在 Azure 门户中注册的应用程序的“客户端 ID (应用程序 ID)”。 Replace the value of ida:ClientId parameter with the Client ID (Application ID) from the application you just registered in the Azure portal.

将新范围添加到 TodoListClient 的 app.configAdd the new scope to the TodoListClient`s app.config

  1. 打开 TodoListClient 项目根文件夹中的 app.config 文件,然后粘贴刚刚在 TodoListServiceScope 参数下为 TodoListService 注册的应用程序中的“应用程序 ID”,并替换字符串 {Enter the Application ID of your TodoListService from the app registration portal}Open the app.config file located in TodoListClient project's root folder and then paste Application ID from the application you just registered for your TodoListService under TodoListServiceScope parameter, replacing the string {Enter the Application ID of your TodoListService from the app registration portal}.

    注意:请确保此 ID 使用以下格式:Note: Make sure it uses the following format:

    api://{TodoListService-Application-ID}/access_as_user

    (其中,{TodoListService-Application-ID} 是表示 TodoListService 的应用程序 ID 的 GUID)。(where {TodoListService-Application-ID} is the GUID representing the Application ID for your TodoListService).

注册客户端应用 (TodoListClient)Register the client app (TodoListClient)

此步骤通过在 Azure 门户中注册新应用程序来配置 TodoListClient 项目。In this step, you configure your TodoListClient project by registering a new application in the Azure portal. 如果客户端和服务器被视为同一个应用程序,则可以重复使用“步骤 2”中注册的同一应用程序。 In the cases where the client and server are considered the same application you may also just reuse the same application registered in the 'Step 2.'.

Azure 门户中注册 TodoListClient 应用程序Register the TodoListClient application in the Azure portal

  1. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.
  2. 选择“新注册”。 Select New registration.
  3. 出现“注册应用程序”页后,请输入应用程序的注册信息: When the Register an application page appears, enter your application's registration information:
    • 在“名称” 部分输入一个会显示给应用用户的有意义的应用程序名称,例如 NativeClient-DotNet-TodoListClientIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example NativeClient-DotNet-TodoListClient.
    • 将“支持的帐户类型”更改为“任何组织目录中的帐户”。 Change Supported account types to Accounts in any organizational directory.
    • 选择“注册” 以创建应用程序。Select Register to create the application.
  4. 在应用的“概述”页中,选择“身份验证”部分。 From the app's Overview page, select the Authentication section.
  5. 选择“API 权限”部分 Select the API permissions section
    • 单击“添加权限” 按钮,然后Click the Add a permission button and then,
    • 选择“我的 API” 选项卡。Select the My APIs tab.
    • 在 API 列表中,选择 AppModelv2-NativeClient-DotNet-TodoListService API 或你为 Web API 输入的名称。In the list of APIs, select the AppModelv2-NativeClient-DotNet-TodoListService API, or the name you entered for the web API.
    • 如果未选中 access_as_user 权限,请将其选中。Check the access_as_user permission if it's not already checked. 如有必要,请使用搜索框。Use the search box if necessary.
    • 选择“添加权限”按钮 Select the Add permissions button

配置 TodoListClient 项目Configure your TodoListClient project

  1. Azure 门户中的“概述”页上,复制“应用程序(客户端) ID”的值 In the Azure portal, in the Overview page copy the value of the Application (client) ID
  2. 打开 TodoListClient 项目根文件夹中的 app.config 文件,然后将该值粘贴到 ida:ClientId 参数值中Open the app.config file located in the TodoListClient project's root folder and then paste the value in the ida:ClientId parameter value

运行项目Run your project

  1. <F5> 运行项目。Press <F5> to run your project. TodoListClient 应会打开。Your TodoListClient should open.
  2. 在右上角选择“登录”,并使用注册应用程序时所用的同一用户或者同一目录中的用户身份登录。 Select Sign in at the top right and sign in with the same user you have used to register your application, or a user in the same directory.
  3. 此时,如果你是首次登录,系统可能会提示你向 TodoListService Web API 许可权限。At this point, if you are signing in for the first time, you may be prompted to consent to TodoListService Web Api.
  4. 登录过程还会请求 access_as_user 范围的访问令牌,以便能够访问 TodoListService Web API 和处理“待办事项”列表。 The sign-in also request the access token to the access_as_user scope to access TodoListService Web Api and manipulate the To-Do list.

为客户端应用程序预先授权Pre-authorize your client application

允许其他目录中的用户访问 Web API 的方法之一是:在 Web API 的预授权应用程序列表中添加来自客户端应用程序的应用程序 ID,从而预先授予客户端应用程序访问 Web API 的权限 。One of the ways to allow users from other directories to access your web API is by pre-authorizing the client applications to access your web API by adding the Application IDs from client applications in the list of pre-authorized applications for your web API. 通过添加预授权的客户端,无需用户同意即可使用 Web API。By adding a pre-authorized client, you will not require user to consent to use your web API. 遵循以下步骤为 Web 应用程序预先授权:Follow the steps below to pre-authorize your Web Application::

  1. 返回 Azure 门户并打开 TodoListService 的属性。Go back to the Azure portal and open the properties of your TodoListService.
  2. 在“公开 API”部分,单击“已授权的客户端应用程序”部分下的“添加客户端应用程序”。 In the Expose an API section, click on Add a client application under the Authorized client applications section.
  3. 在“客户端 ID”字段中,粘贴 TodoListClient 应用程序的应用程序 ID。 In the Client ID field, paste the application ID of the TodoListClient application.
  4. 在“授权范围” 部分中,为此 Web API api://<Application ID>/access_as_user 选择范围。In the Authorized scopes section, select the scope for this web API api://<Application ID>/access_as_user.
  5. 按页面底部的“添加应用程序”按钮。 Press the Add application button at the bottom of the page.

运行项目Run your project

  1. <F5> 运行项目。Press <F5> to run your project. TodoListClient 应会打开。Your TodoListClient should open.
  2. 选择右上角的“登录”(或“清除缓存”/“登录”),然后使用工作或学校帐户登录 。Select Sign in at the top right (or Clear Cache/Sign-in) and then sign-in using a work or school account.

可选:限制应用程序的登录访问权限Optional: Restrict sign-in access to your application

默认情况下,在下载本代码示例并遵循上述步骤将应用程序配置为使用 Azure Active Directory v2 终结点时,与 Azure AD 集成的任何组织中的工作或学校帐户都可以请求令牌并访问你的 Web API。By default, when you download this code sample and configure the application to use the Azure Active Directory v2 endpoint following the preceding steps, Work or school accounts from any organizations that are integrated with Azure AD can request tokens and access your Web API.

若要限制谁可以登录到应用程序,请使用以下选项之一:To restrict who can sign in to your application, use one of the options:

选项 1:将访问权限限制为单个组织(单租户)Option 1: Restrict access to a single organization (single-tenant)

可将应用程序的登录访问权限限制为单个 Azure AD 租户中的用户帐户 - 包括该租户的来宾帐户。 You can restrict sign-in access for your application to only user accounts that are in a single Azure AD tenant - including guest accounts of that tenant. 此方案在业务线应用程序中很常见: This scenario is a common for line-of-business applications:

  1. 打开 App_Start \Startup.Auth 文件,并将传入 OpenIdConnectSecurityTokenProvider 的元数据终结点值更改为 "https://login.partner.microsoftonline.cn/{Tenant ID}/v2.0/.well-known/openid-configuration"(也可以使用租户名称,例如 contoso.partner.onmschina.cn)。Open the App_Start\Startup.Auth file, and change the value of the metadata endpoint that's passed into the OpenIdConnectSecurityTokenProvider to "https://login.partner.microsoftonline.cn/{Tenant ID}/v2.0/.well-known/openid-configuration" (you can also use the Tenant Name, such as contoso.partner.onmschina.cn).
  2. 在同一文件中,将 TokenValidationParameters 中的 ValidIssuer 属性设置为 "https://sts.chinacloudapi.cn/{Tenant ID}/",并将 ValidateIssuer 参数设置为 trueIn the same file, set the ValidIssuer property on the TokenValidationParameters to "https://sts.chinacloudapi.cn/{Tenant ID}/" and the ValidateIssuer argument to true.

选项 2:使用自定义方法来验证颁发者Option 2: Use a custom method to validate issuers

可通过 IssuerValidator 参数实现自定义方法来验证颁发者 。You can implement a custom method to validate issuers by using the IssuerValidator parameter. 有关如何使用此参数的详细信息,请阅读 TokenValidationParameters 类For more information about how to use this parameter, read about the TokenValidationParameters class.

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅以下文章:If you need help, want to report an issue, or want to learn more about your support options, see the following article:

后续步骤Next steps

详细了解 Microsoft 标识平台支持的受保护 Web API 方案:Learn more about the protected web API scenario that the Microsoft identity platform supports: