调用 Web API 的 Web API:代码配置A web API that calls web APIs: Code configuration

注册 Web API 后,可以配置应用程序的代码。After you've registered your web API, you can configure the code for the application.

用于配置 Web API 的代码,配置后它就可以调用下游 Web API,而后者又基于用来保护 Web API 的代码。The code that you use to configure your web API so that it calls downstream web APIs builds on top of the code that's used to protect a web API. 有关详细信息,请参阅受保护的 Web API:应用配置For more information, see Protected web API: App configuration.

Microsoft.Identity.WebMicrosoft.Identity.Web

Microsoft 建议在调用下游 Web API 开发 ASP.NET Core 保护的 API 时,使用 Microsoft.Identity.Web NuGet 包。Microsoft recommends that you use the Microsoft.Identity.Web NuGet package when developing an ASP.NET Core protected API calling downstream web APIs. 请参阅受保护的 Web API:代码配置 | Microsoft.Identity.Web,在 Web API 的上下文中快速了解该库。See Protected web API: Code configuration | Microsoft.Identity.Web for a quick presentation of that library in the context of a web API.

客户端密码或客户端证书Client secrets or client certificates

鉴于 Web API 现在调用了下游 Web API,你需要在 appsettings.json 文件中提供客户端密码或客户端证书。Given that your web API now calls a downstream web API, you need to provide a client secret or client certificate in the appsettings.json file. 还可添加一个部分来指定:You can also add a section that specifies:

  • 下游 Web API 的 URLThe URL of the downstream web API
  • 调用 API 所需的范围The scopes required for calling the API

在下面的示例中,GraphBeta 部分指定了这些设置。In the following example, the GraphBeta section specifies these settings.

{
  "AzureAd": {
    "Instance": "https://login.partner.microsoftonline.cn/",
    "ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
    "TenantId": "common"

   // To call an API
   "ClientSecret": "[Copy the client secret added to the app from the Azure portal]",
   "ClientCertificates": [
  ]
 },
 "GraphBeta": {
    "BaseUrl": "https://microsoftgraph.chinacloudapi.cn/beta",
    "Scopes": "https://microsoftgraph.chinacloudapi.cn/user.read"
    }
}

你可以提供客户端证书,而不是客户端密码。Instead of a client secret, you can provide a client certificate. 以下代码片段演示如何使用存储在 Azure Key Vault 中的证书。The following code snippet shows using a certificate stored in Azure Key Vault.

{
  "AzureAd": {
    "Instance": "https://login.partner.microsoftonline.cn/",
    "ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
    "TenantId": "common"

   // To call an API
   "ClientCertificates": [
      {
        "SourceType": "KeyVault",
        "KeyVaultUrl": "https://msidentitywebsamples.vault.azure.cn",
        "KeyVaultCertificateName": "MicrosoftIdentitySamplesCert"
      }
   ]
  },
  "GraphBeta": {
    "BaseUrl": "https://microsoftgraph.chinacloudapi.cn/beta",
    "Scopes": "https://microsoftgraph.chinacloudapi.cn/user.read"
  }
}

Microsoft.Identity.Web 提供了多种通过配置或代码描述证书的方法。Microsoft.Identity.Web provides several ways to describe certificates, both by configuration or by code. 有关详细信息,请参阅 GitHub 上的 Microsoft.Identity.Web wiki - 使用证书For details, see Microsoft.Identity.Web wiki - Using certificates on GitHub.

Startup.csStartup.cs

Web API 将需要获取下游 API 的令牌。Your web API will need to acquire a token for the downstream API. 可通过在 .AddMicrosoftIdentityWebApi(Configuration) 后面添加 .EnableTokenAcquisitionToCallDownstreamApi() 行来指定它。You specify it by adding the .EnableTokenAcquisitionToCallDownstreamApi() line after .AddMicrosoftIdentityWebApi(Configuration). 此行公开 ITokenAcquisition 服务,它可用于控制器/页面操作。This line exposes the ITokenAcquisition service, that you can use in your controller/pages actions. 不过,正如你将在接下来的两个要点中看到的那样,可更简单地操作。However, as you'll see in the next two bullet points, you can do even simpler. 还需在 Startup.cs 中选择令牌缓存实现,例如 .AddInMemoryTokenCaches()You'll also need to choose a token cache implementation, for example .AddInMemoryTokenCaches(), in Startup.cs:

using Microsoft.Identity.Web;

public class Startup
{
  // ...
  public void ConfigureServices(IServiceCollection services)
  {
  // ...
  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApi(Configuration, Configuration.GetSection("AzureAd"))
            .EnableTokenAcquisitionToCallDownstreamApi()
            .AddInMemoryTokenCaches();
   // ...
  }
  // ...
}

如果你不想亲自获取令牌,Microsoft.Identity.Web 提供两种机制来从另一 API 调用下游 Web API。If you don't want to acquire the token yourself, Microsoft.Identity.Web provides two mechanisms for calling a downstream web API from another API. 选择哪种方式取决于你是要调用 Microsoft Graph 还是调用另一个 API。The option you choose depends on whether you want to call Microsoft Graph or another API.

选项 1:调用 Microsoft GraphOption 1: Call Microsoft Graph

如果要调用 Microsoft Graph,可通过 Microsoft.Identity.Web 在 API 操作中直接使用 GraphServiceClient(由 Microsoft Graph SDK 公开)。If you want to call Microsoft Graph, Microsoft.Identity.Web enables you to directly use the GraphServiceClient (exposed by the Microsoft Graph SDK) in your API actions. 若要公开 Microsoft Graph:To expose Microsoft Graph:

  1. Microsoft.Identity.Web.MicrosoftGraph NuGet 包添加到项目中。Add the Microsoft.Identity.Web.MicrosoftGraph NuGet package to your project.
  2. Startup.cs 文件中 .EnableTokenAcquisitionToCallDownstreamApi() 的后面添加 .AddMicrosoftGraph()Add .AddMicrosoftGraph() after .EnableTokenAcquisitionToCallDownstreamApi() in the Startup.cs file. .AddMicrosoftGraph() 具有多个重写。.AddMicrosoftGraph() has several overrides. 如果使用将配置部分作为参数的重写,代码会变为:Using the override that takes a configuration section as a parameter, the code becomes:
using Microsoft.Identity.Web;

public class Startup
{
  // ...
  public void ConfigureServices(IServiceCollection services)
  {
  // ...
  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApi(Configuration, Configuration.GetSection("AzureAd"))
            .EnableTokenAcquisitionToCallDownstreamApi()
               .AddMicrosoftGraph(Configuration.GetSection("GraphBeta"))
            .AddInMemoryTokenCaches();
   // ...
  }
  // ...
}

选项 2:调用下游 Web API,而不是 Microsoft GraphOption 2: Call a downstream web API other than Microsoft Graph

若要调用下游 Web API 而不是 Microsoft Graph,请使用 Microsoft.Identity.Web 提供的 .AddDownstreamWebApi(),它可请求令牌并调用下游 Web API。To call a downstream API other than Microsoft Graph, Microsoft.Identity.Web provides .AddDownstreamWebApi(), which requests tokens and calls the downstream web API.

using Microsoft.Identity.Web;

public class Startup
{
  // ...
  public void ConfigureServices(IServiceCollection services)
  {
  // ...
  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApi(Configuration, "AzureAd")
            .EnableTokenAcquisitionToCallDownstreamApi()
               .AddDownstreamWebApi("MyApi", Configuration.GetSection("GraphBeta"))
            .AddInMemoryTokenCaches();
   // ...
  }
  // ...
}

与 Web 应用一样,你可以选择各种令牌缓存实现。As with web apps, you can choose various token cache implementations. 有关详细信息,请参阅 GitHub 上的 Microsoft 标识 Web - 令牌缓存序列化For details, see Microsoft identity web - Token cache serialization on GitHub.

下图显示 Microsoft.Identity.Web 的各种可能性以及它们对 Startup.cs 文件的影响 :The following image shows the various possibilities of Microsoft.Identity.Web and their impact on the Startup.cs file:

显示 Startup.cs 中的服务配置选项的框图,说明如何调用 Web API 和指定令牌缓存实现

备注

若要完全理解本文中的代码示例,需要熟悉 ASP.NET Core 基础知识,尤其是依赖关系注入选项To fully understand the code examples here, you need to be familiar with ASP.NET Core fundamentals, and in particular with dependency injection and options.

也可以参阅 Node.js 和 Azure Functions 中的 OBO 流实现示例。You can also see an example of OBO flow implementation in Node.js and Azure Functions.

协议Protocol

有关 OBO 协议的详细信息,请参阅 Microsoft 标识平台和 OAuth 2.0 代理流For more information about the OBO protocol, see Microsoft identity platform and OAuth 2.0 On-Behalf-Of flow.

后续步骤Next steps

转到此方案中的下一篇文章:获取应用的令牌Move on to the next article in this scenario, Acquire a token for the app.