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

在本快速入门中,你将下载并运行一个代码示例,该示例演示如何通过将访问其资源限制为仅授权帐户来保护 ASP.NET Web API。In this quickstart, you download and run a code sample that demonstrates how to protect an ASP.NET web API by restricting access to its resources to authorized accounts only. 该示例支持对任何 Azure Active Directory (Azure AD) 组织中的帐户进行授权。The sample supports authorization of accounts in any Azure Active Directory (Azure AD) organization.

本文还使用 Windows Presentation Foundation (WPF) 应用演示如何请求访问令牌来访问 Web API。The article also uses a Windows Presentation Foundation (WPF) app to demonstrate how you can request an access token to access a web API.

先决条件Prerequisites

克隆或下载示例Clone or download the sample

可以通过以下两种方式之一获取该示例:You can obtain the sample in either of two ways:

提示

为了避免在 Windows 中出现路径长度限制导致的错误,建议将存档解压或将存储库克隆到驱动器根附近的目录中。To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.

注册 Web APIRegister your web API

本部分中将在 Azure 门户的“应用注册”中注册 Web API。In this section, you register your web API in App registrations in the Azure portal.

选择 Azure AD 租户Choose your Azure AD tenant

若要手动注册应用,请选择要在其中创建应用的 Azure Active Directory (Azure AD) 租户。To register your apps manually, choose the Azure Active Directory (Azure AD) tenant where you want to create your apps.

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 如果你有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器 ,选择你想要使用的租户。

注册 TodoListService 应用Register the TodoListService app

  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. 输入应用程序的名称(例如 AppModelv2-NativeClient-DotNet-TodoListService)。Enter a Name for your application, for example AppModelv2-NativeClient-DotNet-TodoListService. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.

  6. 在“支持的帐户类型”下,选择“任何组织目录中的帐户” 。For Supported account types, select Accounts in any organizational directory.

  7. 选择“注册”以创建应用程序。Select Register to create the application.

  8. 在应用的“概述”页上,找到“应用程序(客户端) ID”值,然后记下该值以供后续使用 。On the app Overview page, look for the Application (client) ID value, and then record it for later use. 你将需要使用该值为此项目配置 Visual Studio 配置文件(即 TodoListService\Web.config 文件中的 ClientId)。You'll need it to configure the Visual Studio configuration file for this project (that is, ClientId in the TodoListService\Web.config file).

  9. 在“管理”下,选择“公开 API” > “添加范围” 。Under Manage, select Expose an API > Add a scope. 通过选择“保存并继续”来接受建议的应用程序 ID URI (api://{clientId}),然后输入以下信息:Accept the proposed Application ID URI (api://{clientId}) by selecting Save and continue, and then enter the following information:

    1. 对于“范围名称”,输入 access_as_userFor Scope name, enter access_as_user.
    2. 对于“谁能同意?”,请确保选择了“管理员和用户”选项 。For Who can consent, ensure that the Admins and users option is selected.
    3. 在“管理员同意显示名称”框中,输入 Access TodoListService as a userIn the Admin consent display name box, enter Access TodoListService as a user.
    4. 在“管理员同意说明”框中,输入 Accesses the TodoListService web API as a userIn the Admin consent description box, enter Accesses the TodoListService web API as a user.
    5. 在“用户同意显示名称”框中,输入 Access TodoListService as a userIn the User consent display name box, enter Access TodoListService as a user.
    6. 在“用户同意说明”框中,输入 Accesses the TodoListService web API as a userIn the User consent description box, enter Accesses the TodoListService web API as a user.
    7. 对于“状态”,保留“启用” 。For State, keep Enabled.
  10. 选择“添加范围”。Select Add scope.

配置服务项目Configure the service project

按照以下步骤,配置服务项目以匹配注册的 Web API:Configure the service project to match the registered web API by doing the following:

  1. 在 Visual Studio 中打开解决方案,然后在“TodoListService”项目的根目录下打开 Web.config 文件。Open the solution in Visual Studio, and then open the Web.config file under the root of the TodoListService project.

  2. ida:ClientId 参数的值替换为刚才在“应用注册”门户中注册的应用程序中的客户端 ID(应用程序 ID)值。Replace the value of the ida:ClientId parameter with the Client ID (Application ID) value from the application you just registered in the App registrations portal.

将新范围添加到 app.config 文件Add the new scope to the app.config file

若要将新范围添加到 TodoListClient 的 app.config 文件中,请执行以下操作:To add the new scope to the TodoListClient app.config file, do the following:

  1. 在 TodoListClient 项目根文件夹中,打开 app.config 文件。In the TodoListClient project root folder, open the app.config file.

  2. 将 TodoListService 项目中刚注册的应用程序 ID 粘贴到 TodoListServiceScope 参数中,并替换 {Enter the Application ID of your TodoListService from the app registration portal} 字符串。Paste the Application ID from the application you just registered for your TodoListService project in the TodoListServiceScope parameter, replacing the {Enter the Application ID of your TodoListService from the app registration portal} string.

备注

请确保应用程序 ID 使用以下格式:api://{TodoListService-Application-ID}/access_as_user(其中 {TodoListService-Application-ID} 是表示 TodoListService 应用的应用程序 ID 的 GUID)。Make sure that the Application ID uses the following format: api://{TodoListService-Application-ID}/access_as_user (where {TodoListService-Application-ID} is the GUID representing the Application ID for your TodoListService app).

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

本部分将在 Azure 门户的“应用注册”中注册 TodoListClient 应用,然后在 TodoListClient 项目中配置代码。In this section, you register your TodoListClient app in App registrations in the Azure portal, and then configure the code in the TodoListClient project. 如果客户端和服务器视为相同的应用程序,则可重复使用在“步骤 2”中注册的同一应用程序。If the client and server are considered the same application, you can reuse the application that's registered in step 2.

注册应用Register the app

若要注册 TodoListClient 应用,请执行以下操作:To register the TodoListClient app, do the following:

  1. 转到面向开发人员的 Microsoft 标识平台的应用注册门户。Go to the Microsoft identity platform for developers App registrations portal.

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

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

    1. 在“名称”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 NativeClient-DotNet-TodoListClient 。In the Name section, enter a meaningful application name that will be displayed to users of the app (for example, NativeClient-DotNet-TodoListClient).
    2. 在“支持的帐户类型”下,选择“任何组织目录中的帐户” 。For Supported account types, select Accounts in any organizational directory.
    3. 选择“注册”以创建应用程序。Select Register to create the application.

    备注

    在 TodoListClient 项目的 app.config 文件中,将 ida:Tenant 的默认值设置为 commonIn the TodoListClient project app.config file, the default value of ida:Tenant is set to common. 可能的值为:The possible values are:

    • common:可以使用工作或学校帐户登录(因为你在步骤 3b 中选择了“任何组织目录中的帐户”)。common: You can sign in by using a work or school account (because you selected Accounts in any organizational directory in step 3b).
    • organizations:可使用工作或学校帐户登录。organizations: You can sign in by using a work or school account.
  4. 在应用的“概述”页面,选择“身份验证”,然后执行以下操作 :On the app Overview page, select Authentication, and then do the following:

    1. 在“平台配置”下,选择“添加平台”按钮 。Under Platform configurations, select the Add a platform button.
    2. 对于“移动和桌面应用程序”,选择“移动和桌面应用程序” 。For Mobile and desktop applications, select Mobile and desktop applications.
    3. 对于“重定向 URI”,请选择“ https://login.partner.microsoftonline.cn/common/oauth2/nativeclient ”复选框 。For Redirect URIs, select the https://login.partner.microsoftonline.cn/common/oauth2/nativeclient check box.
    4. 选择“配置” 。Select Configure.
  5. 选择“API 权限”,然后执行以下操作:Select API permissions, and then do the following:

    1. 选择“添加权限”按钮。Select the Add a permission button.
    2. 选择“我的 API”选项卡。Select the My APIs tab.
    3. 在 API 列表中,选择 AppModelv2-NativeClient-DotNet-TodoListService API 或选择为 Web API 输入的名称。In the list of APIs, select AppModelv2-NativeClient-DotNet-TodoListService API or the name you entered for the web API.
    4. 如果“access_as_user”权限复选框未处于选中状态,请将其选中。Select the access_as_user permission check box if it's not already selected. 如有必要,请使用搜索框。Use the Search box if necessary.
    5. 选择“添加权限”按钮。Select the Add permissions button.

配置项目Configure your project

若要配置 TodoListClient 项目,请执行以下操作:To configure your TodoListClient project, do the following:

  1. 在“应用注册门户”的“概述”页中,复制“应用程序(客户端) ID”的值 。In the App registrations portal, on the Overview page, copy the value of the Application (client) ID.

  2. 打开位于“TodoListClient”项目根文件夹中的 app.config 文件,然后将应用程序 ID 值粘贴到 ida:ClientId 参数中。From the TodoListClient project root folder, open the app.config file, and then paste the Application ID value in the ida:ClientId parameter.

运行 TodoListClient 项目Run your TodoListClient project

若要运行 TodoListClient 项目,请执行以下操作:To run your TodoListClient project, do the following:

  1. 按 F5 打开 TodoListClient 项目。Press F5 to open your TodoListClient project. 项目页面应打开。The project page should open.

  2. 选择右上角的“登录”,然后使用注册应用程序时所用的同一凭据登录,或以同一目录中的用户身份登录。At the upper right, select Sign in, and then sign in with the same credentials you used to register your application, or sign in as a user in the same directory.

    如果你是首次登录,系统可能会提示你同意 TodoListService Web API。If you're signing in for the first time, you might be prompted to consent to the TodoListService web API.

    登录时还需要请求 access_as_user 范围的访问令牌,用于访问 TodoListService Web API 并处理“待办事项”列表 。To help you access the TodoListService web API and manipulate the To-Do list, the sign-in also requests an access token to the access_as_user scope.

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

允许其他目录中的用户访问 Web API 的一种方法是,预先授权客户端应用程序访问 Web API。One way you can allow users from other directories to access your web API is to pre-authorize the client application to access your web API. 为此,可将客户端应用中的应用程序 ID 添加到 Web API 的预授权应用程序列表中。You do this by adding the Application ID from the client app to the list of pre-authorized applications for your web API. 添加预授权客户端,即表示你允许用户访问你的 Web API,而不必再征求你的同意。By adding a pre-authorized client, you're allowing users to access your web API without having to provide consent. 若要预授权客户端应用,请执行以下操作:To pre-authorize your client app, do the following:

  1. 在“应用注册”门户中,打开 TodoListService 应用的属性。In the App registrations portal, open the properties of your TodoListService app.
  2. 在“公开 API”部分,选择“授权的客户端应用程序”部分下的“添加客户端应用程序” 。In the Expose an API section, under Authorized client applications, select Add a client application.
  3. 在“客户端 ID”框中,粘贴 TodoListClient 应用的应用程序 ID。In the Client ID box, paste the Application ID of the TodoListClient app.
  4. 在“授权范围”部分中,为此 api://<Application ID>/access_as_user Web API 选择范围。In the Authorized scopes section, select the scope for the api://<Application ID>/access_as_user web API.
  5. 选择“添加应用程序”。Select Add application.

运行项目Run your project

  1. 按 F5 运行项目。Press F5 to run your project. 随即应打开 TodoListClient 应用。Your TodoListClient app should open.
  2. 在右上方选择“登录”,然后使用工作或学校帐户登录。At the upper right, select Sign in, and then sign in by using a work or school account.

可选:限制对特定用户的登录访问Optional: Limit sign-in access to certain users

默认情况下,当你执行前面的步骤时,任何集成了 Azure AD 的组织的工作或学校帐户都可以请求令牌并访问你的 Web API。By default, when you've followed the preceding steps, any work or school accounts from organizations that are integrated with Azure AD can request tokens and access your web API.

若要指定可登录应用程序的人员,请使用以下某个选项:To specify who can sign in to your application, use one of the following options:

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

可以仅限单个 Azure AD 租户中的用户帐户(包括该租户的“来宾帐户”)登录应用程序。You can limit sign-in access to your application to user accounts that are in a single Azure AD tenant, including guest accounts of that tenant. 此场景对业务线应用程序较为常见:This scenario is 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"Open the App_Start\Startup.Auth file, and then 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". 还可使用租户名称,例如 contoso.partner.onmschina.cnYou 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 set 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 this parameter, see TokenValidationParameters class.

帮助和支持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

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