您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Microsoft 标识平台保护 ASP.NET Core Web APIQuickstart: Protect an ASP.NET Core web API with the Microsoft identity platform

在本快速入门中,我们将下载一个 ASP.NET Core Web API 代码示例并查看其对资源的访问权限限制为仅授权帐户的方式。In this quickstart, you download an ASP.NET Core web API code sample and review the way it restricts resource access to authorized accounts only. 该示例支持对任何 Azure Active Directory (Azure AD) 组织中的个人 Microsoft 帐户和帐户进行授权。The sample supports authorization of personal Microsoft accounts and accounts in any Azure Active Directory (Azure AD) organization.

先决条件Prerequisites

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

首先,在 Azure AD 租户中注册 Web API,并通过执行以下步骤来添加范围:First, register the web API in your Azure AD tenant and add a scope by following 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. 对于“名称”,请输入应用程序名称。For Name, enter a name for your application. 例如,输入 AspNetCoreWebApi-QuickstartFor example, enter AspNetCoreWebApi-Quickstart. 应用的用户会看到此名称,你稍后可对其进行更改。Users of your app will see this name, and you can change it later.
  6. 选择“注册” 。Select Register.
  7. 在“管理”下,选择“公开 API” > “添加范围” 。Under Manage, select Expose an API > Add a scope. 针对 应用程序 ID URI,通过选择 保存并继续 来接受默认,然后输入以下信息:For Application ID URI, accept the default by selecting Save and continue, and then enter the following details:
    • 范围名称access_as_userScope name: access_as_user
    • 谁能同意? :管理员和用户Who can consent?: Admins and users
    • 管理员许可显示名称Access AspNetCoreWebApi-QuickstartAdmin consent display name: Access AspNetCoreWebApi-Quickstart
    • 管理员许可说明Allows the app to access AspNetCoreWebApi-Quickstart as the signed-in user.Admin consent description: Allows the app to access AspNetCoreWebApi-Quickstart as the signed-in user.
    • 用户同意显示名称Access AspNetCoreWebApi-QuickstartUser consent display name: Access AspNetCoreWebApi-Quickstart
    • 用户同意说明Allow the application to access AspNetCoreWebApi-Quickstart on your behalf.User consent description: Allow the application to access AspNetCoreWebApi-Quickstart on your behalf.
    • 状态已启用State: Enabled
  8. 选择“添加范围”以完成范围添加。Select Add scope to complete the scope addition.

步骤 2:下载 ASP.NET Core 项目Step 2: Download the ASP.NET Core project

提示

若要避免由于 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.

步骤 3:配置 ASP.NET Core 项目Step 3: Configure the ASP.NET Core project

在此步骤中,将示例代码配置为使用之前创建的应用注册。In this step, configure the sample code to work with the app registration that you created earlier.

  1. 将 .zip 存档提取到驱动器根附近的文件夹中。Extract the .zip archive into a folder near the root of your drive. 例如,解压到 C:\Azure-Samples。For example, extract into C:\Azure-Samples.

    建议将存档解压到驱动器根附近的目录中,以避免在 Windows 上出现路径长度限制导致的错误。We recommend extracting the archive into a directory near the root of your drive to avoid errors caused by path length limitations on Windows.

  2. 在代码编辑器的 webapi 文件夹中打开解决方案。Open the solution in the webapi folder in your code editor.

  3. 打开 appsettings.json 文件,并修改以下代码:Open the appsettings.json file and modify the following code:

    "ClientId": "Enter_the_Application_Id_here",
    "TenantId": "Enter_the_Tenant_Info_Here"
    
    • Enter_the_Application_Id_here 替换为在 Azure 门户中注册的应用程序的应用程序(客户端)ID。Replace Enter_the_Application_Id_here with the application (client) ID of the application that you registered in the Azure portal. 可以在应用的“概述”页上找到应用程序(客户端)ID。You can find the application (client) ID on the app's Overview page.
    • Enter_the_Tenant_Info_Here 替换为以下其中一项:Replace Enter_the_Tenant_Info_Here with one of the following:
      • 如果应用程序支持“仅限此组织目录中的帐户”,请将此值替换为目录(租户)ID(GUID)或租户名称(例如,contoso.onmicrosoft.com)。If your application supports Accounts in this organizational directory only, replace this value with the directory (tenant) ID (a GUID) or tenant name (for example, contoso.onmicrosoft.com). 你可以在应用的“概述”页上找到目录(租户)ID。You can find the directory (tenant) ID on the app's Overview page.
      • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为 organizationsIf your application supports Accounts in any organizational directory, replace this value with organizations.
      • 如果应用程序支持“所有 Microsoft 帐户用户”,请将该值保留为 commonIf your application supports All Microsoft account users, leave this value as common.

在此快速入门中,请不要更改 appsettings.json 文件中的任何其他值。For this quickstart, don't change any other values in the appsettings.json file.

示例工作原理How the sample works

Web API 从客户端应用程序接收令牌,Web API 中的代码验证该令牌。The web API receives a token from a client application, and the code in the web API validates the token. 方案:受保护的 Web API 中详细说明了此方案。This scenario is explained in more detail in Scenario: Protected web API.

Startup 类Startup class

Microsoft.AspNetCore.Authentication 中间件使用托管进程启动时执行的 Startup 类。The Microsoft.AspNetCore.Authentication middleware uses a Startup class that's executed when the hosting process starts. 在其 ConfigureServices 方法中,调用了 Microsoft.Identity.Web 提供的 AddMicrosoftIdentityWebApi 扩展方法。In its ConfigureServices method, the AddMicrosoftIdentityWebApi extension method provided by Microsoft.Identity.Web is called.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
    }

AddAuthentication() 方法配置服务以添加基于 JwtBearer 的身份验证。The AddAuthentication() method configures the service to add JwtBearer-based authentication.

包含 .AddMicrosoftIdentityWebApi 的行会向 Web API 添加 Microsoft 标识平台授权。The line that contains .AddMicrosoftIdentityWebApi adds the Microsoft identity platform authorization to your web API. 然后对其进行配置,使其根据 appsettings.json 配置文件的 AzureAD 部分中的信息来验证 Microsoft 标识平台颁发的访问令牌:It's then configured to validate access tokens issued by the Microsoft identity platform based on the information in the AzureAD section of the appsettings.json configuration file:

appsettings.json 密钥appsettings.json key 说明Description
ClientId Azure 门户中注册的应用程序的“应用程序(客户端) ID”。Application (client) ID of the application registered in the Azure portal.
Instance 用户进行身份验证时使用的安全令牌服务 (STS) 终结点。Security token service (STS) endpoint for the user to authenticate. 此值通常为 https://login.microsoftonline.com/,指示 Azure 公有云。This value is typically https://login.microsoftonline.com/, indicating the Azure public cloud.
TenantId 租户的名称或其租户 ID (GUID),或使用工作帐户或学校帐户或 Microsoft 个人帐户进行用户登录时常用的名称。Name of your tenant or its tenant ID (a GUID), or common to sign in users with work or school accounts or Microsoft personal accounts.

Configure() 方法包含两个重要的方法 app.UseAuthentication()app.UseAuthorization(),这些方法实现了命名功能:The Configure() method contains two important methods, app.UseAuthentication() and app.UseAuthorization(), that enable their named functionality:

// The runtime calls this method. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // more code
    app.UseAuthentication();
    app.UseAuthorization();
    // more code
}

保护控制器、控制器的方法或 Razor 页Protecting a controller, a controller's method, or a Razor page

可以使用 [Authorize] 属性保护控制器或控制器方法。You can protect a controller or controller methods by using the [Authorize] attribute. 此属性只允许经过身份验证的用户,从而限制对控制器或方法的访问。This attribute restricts access to the controller or methods by allowing only authenticated users. 如果用户尚未通过身份验证,可以启动身份验证质询来访问控制器。An authentication challenge can be started to access the controller if the user isn't authenticated.

namespace webapi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase

验证控制器中的范围Validation of scope in the controller

API 中的代码通过使用 HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); 来验证令牌中是否涵盖了所需范围:The code in the API verifies that the required scopes are in the token by using HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);:

namespace webapi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        // The web API will only accept tokens 1) for users, and 2) having the "access_as_user" scope for this API
        static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

            // some code here
        }
    }
}

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

包含此 ASP.NET Core Web API 代码示例的 GitHub 存储库包含说明和更多代码示例,这些示例向你展示如何:The GitHub repository that contains this ASP.NET Core web API code sample includes instructions and more code samples that show you how to:

  • 向新的 ASP.NET Core Web API 添加身份验证。Add authentication to a new ASP.NET Core web API.
  • 从桌面应用程序调用 Web API。Call the web API from a desktop application.
  • 调用下游 API,如 Microsoft Graph 和其他 Microsoft API。Call downstream APIs like Microsoft Graph and other Microsoft APIs.