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

用于登录用户的 Web 应用方案中所述,Web 应用使用 OAuth 2.0 授权代码流来登录用户。As shown in the Web app that signs in users scenario, the web app uses the OAuth 2.0 authorization code flow to sign the user in. 此流有两个步骤:This flow has two steps:

  1. 请求获取授权代码。Request an authorization code. 此部分将私密对话和用户一起委派给 Microsoft 标识平台。This part delegates a private dialogue with the user to the Microsoft identity platform. 在此对话期间,用户登录,并同意使用 Web API。During that dialogue, the user signs in and consents to the use of web APIs. 当此私密对话成功结束时,Web 应用会在其重定向 URI 中收到一个授权代码。When the private dialogue ends successfully, the web app receives an authorization code on its redirect URI.
  2. 通过兑换授权代码来请求获取 API 的访问令牌。Request an access token for the API by redeeming the authorization code.

用于登录用户的 Web 应用方案只涉及第一步。The Web app that signs in users scenarios covered only the first step. 在本文中,你将学习如何修改 Web 应用,使其不仅能登录用户,而且现在还能调用 Web API。Here you learn how to modify your web app so that it not only signs users in but also now calls web APIs.

支持 Web 应用方案的库Libraries that support web-app scenarios

Microsoft 身份验证库 (MSAL) 中的以下库支持 Web 应用的授权代码流:The following libraries in the Microsoft Authentication Library (MSAL) support the authorization code flow for web apps:

MSAL 库MSAL library 说明Description
MSAL.NET
MSAL.NETMSAL.NET
支持 .NET Framework 和 .NET Core 平台。Support for .NET Framework and .NET Core platforms. 不支持通用 Windows 平台 (UWP)、Xamarin.iOS 和 Xamarin.Android,因为这些平台用于生成公共客户端应用。Not supported are Universal Windows Platform (UWP), Xamarin.iOS, and Xamarin.Android, because those platforms are used to build public client applications. 对于 ASP.NET Core Web 应用和 Web API,MSAL.NET 会封装在名为 Microsoft.Identity.Web 的更高级别库中For ASP.NET Core web apps and web APIs, MSAL.NET is encapsulated in a higher level library named Microsoft.Identity.Web
MSAL Python
适用于 Python 的 MSALMSAL for Python
支持 Python Web 应用。Support for Python web applications.
MSAL Java
适用于 Java 的 MSALMSAL for Java
支持 Java Web 应用。Support for Java web applications.

选择你感兴趣的平台的选项卡:Select the tab for the platform you're interested in:

若要让 Web 应用可以在使用 Microsoft.Identity.Web 时调用受保护的 API,只需调用 AddWebAppCallsProtectedWebApi,并指定令牌缓存序列化格式(例如,内存中令牌缓存)即可:To enable your web app to call protected APIs when using Microsoft.Identity.Web, you need only to call AddWebAppCallsProtectedWebApi and specify a token cache serialization format (for example, in-memory token cache):

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // more code here

    services.AddMicrosoftIdentityWebAppAuthentication(Configuration,
                                                      "AzureAd")
            .EnableTokenAcquisitionToCallDownstreamApi(
                    initialScopes: new string[] { "https://microsoftgraph.chinacloudapi.cn/user.read" })
                .AddInMemoryTokenCaches();

    // more code here
}

若要详细了解令牌缓存,请参阅令牌缓存序列化选项If you're interested in understanding more about the token cache, see Token cache serialization options

备注

若要完全理解本文中的代码示例,需要熟悉 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.

兑换授权代码的代码Code that redeems the authorization code

Microsoft.Identity.Web 通过设置正确的 OpenID Connect 设置、订阅代码接收的事件和兑换代码来简化代码。Microsoft.Identity.Web simplifies your code by setting the correct OpenID Connect settings, subscribing to the code received event, and redeeming the code. 兑换授权代码不需要其他任何代码。No additional code is required to redeem the authorization code. 请参阅 Microsoft.Identity.Web 源代码,详细了解其原理。See Microsoft.Identity.Web source code for details on how this works.

保密客户端应用还可以使用客户端证书或客户端断言(而不是客户端密码)来证明其标识。Instead of a client secret, the confidential client application can also prove its identity by using a client certificate, or a client assertion. 使用客户端断言是一种高级方案,客户端断言中对此进行了详细说明。The use of client assertions is an advanced scenario, detailed in Client assertions.

令牌缓存Token cache

重要

Web 应用或 Web API 的令牌缓存实现不同于桌面应用的实现,后者通常是基于文件的。The token-cache implementation for web apps or web APIs is different from the implementation for desktop applications, which is often file based. 出于安全性和性能方面的原因,请务必确保对于 Web 应用和 Web API,每个用户帐户都有一个令牌缓存。For security and performance reasons, it's important to ensure that for web apps and web APIs there is one token cache per user account. 必须为每个帐户序列化令牌缓存。You must serialize the token cache for each account.

ASP.NET Core 教程使用依赖关系注入,让你能够在应用的 Startup.cs 文件中确定令牌缓存实现。The ASP.NET core tutorial uses dependency injection to let you decide the token cache implementation in the Startup.cs file for your application. Microsoft.Identity.Web 随附了令牌缓存序列化中所述的预生成令牌缓存序列化程序。Microsoft.Identity.Web comes with pre-built token-cache serializers described in Token cache serialization. 一个有意思的地方是,可以选择 ASP.NET Core 分布式内存缓存An interesting possibility is to choose ASP.NET Core distributed memory caches:

// Use a distributed token cache by adding:
    services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd")
            .EnableTokenAcquisitionToCallDownstreamApi(
                initialScopes: new string[] { "https://microsoftgraph.chinacloudapi.cn/user.read" })
            .AddDistributedTokenCaches();

// Then, choose your implementation.
// For instance, the distributed in-memory cache (not cleared when you stop the app):
services.AddDistributedMemoryCache();

// Or a Redis cache:
services.AddStackExchangeRedisCache(options =>
{
 options.Configuration = "localhost";
 options.InstanceName = "SampleInstance";
});

// Or even a SQL Server token cache:
services.AddDistributedSqlServerCache(options =>
{
 options.ConnectionString = _config["DistCache_ConnectionString"];
 options.SchemaName = "dbo";
 options.TableName = "TestCache";
});

有关令牌缓存提供程序的详细信息,另请参阅 Microsoft.Identity.Web 的令牌缓存序列化一文,以及 Web 应用教程的 ASP.NET Core Web 应用教程 | 令牌缓存部分。For details about the token-cache providers, see also Microsoft.Identity.Web's Token cache serialization article, as well as the ASP.NET Core Web app tutorials | Token caches phase of the web apps tutorial.

后续步骤Next steps

此时,当用户登录时,令牌存储在令牌缓存中。At this point, when the user signs in, a token is stored in the token cache. 让我们来看看随后是如何在 Web 应用的其他部分中使用它的。Let's see how it's then used in other parts of the web app.