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

在本快速入门中,我们将下载一个 ASP.NET Core Web API 代码示例并查看其代码,该代码将对资源的访问权限限制为仅授权帐户。In this quickstart, you download an ASP.NET Core web API code sample and review its code that restricts access to resources to authorized accounts only. 该示例支持对任何 Azure Active Directory (Azure AD) 组织中的帐户进行授权。The sample supports authorization of 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, then New registration.
  5. 输入应用程序的名称(例如 AspNetCoreWebApi-Quickstart)。Enter a Name for your application, for example AspNetCoreWebApi-Quickstart. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
  6. 选择“注册” 。Select Register.
  7. 在“管理”下,选择“公开 API” Under Manage, select Expose an API
  8. 选择“添加范围”,并选择“保存并继续”以接受默认的“应用程序 ID URI” 。Select Add a scope and select Save and continue to accept the default Application ID URI.
  9. 在“添加范围”窗格中,输入以下值:In the Add a scope pane, enter the following values:
    • 范围名称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
  10. 选择“添加范围”以完成范围添加。Select Add scope to complete the scope addition.

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

步骤 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 you created earlier.

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

  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:

    "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 you registered in the Azure portal. 可以在应用的“概览”页中找到“应用程序(客户端) ID”。You can find Application (client) ID in the app's Overview page.
    • Enter_the_Tenant_Info_Here 替换为以下其中一项:Replace Enter_the_Tenant_Info_Here with one of the following:
      • 如果应用程序支持“仅限此组织目录中的帐户”,请将此值替换为“目录(租户) ID”(GUID) 或“租户名称”(例如 contoso.partner.onmschina.cn) 。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.partner.onmschina.cn). 你可以在应用的”概述”页上找到“目录(租户) 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

在此快速入门中,请不要更改 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 initializes. 在其 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 containing .AddMicrosoftIdentityWebApi adds 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 endpoint 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.partner.microsoftonline.cn/,指示 Azure 中国云。This value is typically https://login.partner.microsoftonline.cn/, indicating the Azure China cloud.
TenantId 该值是租户的名称或其租户 ID (GUID),或者是 common(如果使用工作帐户或学校帐户进行用户登录)。Name of your tenant or its tenant ID (a GUID), or common to sign in users with work or school accounts.

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

// This method gets called by the runtime. 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 页Protect a controller, a controller's method, or a Razor page

可以使用 [Authorize] 属性保护控制器或控制器方法。You can protect a controller or controller methods using the [Authorize] attribute. 此属性通过仅允许经过身份验证的用户,来限制对控制器或方法的访问,这意味着如果用户未经身份验证,则可以启动身份验证质询来访问控制器。This attribute restricts access to the controller or methods by only allowing authenticated users, which means that 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

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

然后,API 中的代码通过使用 HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); 来验证令牌中是否涵盖了所需范围The code in the API then 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 would like 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 APICall the web API from a desktop application
  • 调用下游 API,如 Microsoft Graph 和其他 Microsoft APICall downstream APIs like Microsoft Graph and other Microsoft APIs