将应用程序迁移到 MSAL.NETMigrating applications to MSAL.NET

适用于 .NET 的 Microsoft 身份验证库 (MSAL.NET) 与适用于 .NET 的 Azure AD 身份验证库 (ADAL.NET) 用于对 Azure AD 实体进行身份验证,以及从 Azure AD 请求令牌。Both Microsoft Authentication Library for .NET (MSAL.NET) and Azure AD Authentication Library for .NET (ADAL.NET) are used to authenticate Azure AD entities and request tokens from Azure AD. 截止目前,大多数开发人员都是通过 Azure AD 身份验证库 (ADAL) 来请求令牌,使用面向开发人员的 Azure AD 平台 (v1.0) 来对 Azure AD 标识(工作和学校帐户)进行身份验证。Up until now, most developers have worked with Azure AD for developers platform (v1.0) to authenticate Azure AD identities (work and school accounts) by requesting tokens using Azure AD Authentication Library (ADAL). 使用 MSAL:Using MSAL:

  • 你可以对更广泛的一组 Microsoft 标识进行身份验证(通过 Azure AD B2C 验证 Azure AD 标识以及社交和本地帐户),因为它使用 Microsoft 标识平台终结点,you can authenticate a broader set of Microsoft identities (Azure AD identities and social and local accounts through Azure AD B2C) as it uses the Microsoft identity platform endpoint,
  • 你的用户将获得最佳单一登录体验。your users will get the best single-sign-on experience.
  • 应用程序可以启用增量许可,可以更轻松地为条件访问提供支持your application can enable incremental consent, and supporting Conditional Access is easier
  • 你将从创新中受益。you benefit from the innovation.

MSAL.NET 现在是建议用于 Microsoft 标识平台的身份验证库MSAL.NET is now the recommended auth library to use with the Microsoft identity platform. 不会使用 ADAL.NET 实现任何新功能。No new features will be implemented on ADAL.NET. 工作的重点是改进 MSAL。The efforts are focused on improving MSAL.

本文介绍适用于 .NET 的 Microsoft 身份验证库 (MSAL.NET) 与适用于 .NET 的 Azure AD 身份验证库 (ADAL.NET) 之间的差异,并帮助你迁移到 MSAL。This article describes the differences between the Microsoft Authentication Library for .NET (MSAL.NET) and Azure AD Authentication Library for .NET (ADAL.NET) and helps you migrate to MSAL.

ADAL 与 MSAL 应用之间的差异Differences between ADAL and MSAL apps

在大多数情况下都可以使用 MSAL.NET 和 Microsoft 标识平台终结点,这是最新一代的 Microsoft 身份验证库。In most cases you want to use MSAL.NET and the Microsoft identity platform endpoint, which is the latest generation of Microsoft authentication libraries. 使用 MSAL.NET 可以获取通过 Azure AD(工作和学校帐户)或 Azure AD B2C 登录到应用程序的用户的令牌。Using MSAL.NET, you acquire tokens for users signing-in to your application with Azure AD (work and school accounts) or Azure AD B2C.

如果你已熟悉面向开发人员的 Azure AD (v1.0) 终结点(和 ADAL.NET),请阅读 Microsoft 标识平台 (v2.0) 终结点有何不同?If you are already familiar with the Azure AD for developers (v1.0) endpoint (and ADAL.NET), you might want to read What's different about the Microsoft identity platform (v2.0) endpoint?.

但是,如果应用程序需要使用早期版本的 Active Directory 联合身份验证服务 (ADFS) 将用户登录,则你仍然需要使用 ADAL.NET。However, you still need to use ADAL.NET if your application needs to sign in users with earlier versions of Active Directory Federation Services (ADFS). 有关详细信息,请参阅 ADFS 支持For more information, see ADFS support.

下图汇总了 ADAL.NET 与 MSAL.NET 之间的一些差异 代码比较The following picture summarizes some of the differences between ADAL.NET and MSAL.NET Side-by-side code

NuGet 包和命名空间NuGet packages and Namespaces

ADAL.NET 是从 Microsoft.IdentityModel.Clients.ActiveDirectory NuGet 包使用的。ADAL.NET is consumed from the Microsoft.IdentityModel.Clients.ActiveDirectory NuGet package. 要使用的命名空间为 Microsoft.IdentityModel.Clients.ActiveDirectorythe namespace to use is Microsoft.IdentityModel.Clients.ActiveDirectory.

若要使用 MSAL.NET,需要添加 Microsoft.Identity.Client NuGet 包并使用 Microsoft.Identity.Client 命名空间To use MSAL.NET you will need to add the Microsoft.Identity.Client NuGet package, and use the Microsoft.Identity.Client namespace

范围不是资源Scopes not resources

ADAL.NET 获取资源的令牌,但 MSAL.NET 获取范围的令牌。 ADAL.NET acquires tokens for resources, but MSAL.NET acquires tokens for scopes. 许多 MSAL.NET AcquireToken 重写都需要名为 scopes(IEnumerable<string> scopes) 的参数。A number of MSAL.NET AcquireToken overrides require a parameter called scopes(IEnumerable<string> scopes). 此参数是一个简单的字符串列表,这些字符串声明所需的权限和请求的资源。This parameter is a simple list of strings that declare the desired permissions and resources that are requested. 已知的范围是 Microsoft Graph 范围Well known scopes are the Microsoft Graph's scopes.

在 MSAL.NET 中也可以访问 v1.0 资源。It's also possible in MSAL.NET to access v1.0 resources. 请参阅 v1.0 应用程序的范围中的详细信息。See details in Scopes for a v1.0 application.

核心类Core classes

  • ADAL.NET 使用 AuthenticationContext 来表示通过颁发机构与安全令牌服务 (STS) 或授权服务器建立的连接。ADAL.NET uses AuthenticationContext as the representation of your connection to the Security Token Service (STS) or authorization server, through an Authority. 相比之下,MSAL.NET 是围绕客户端应用程序设计的。On the contrary, MSAL.NET is designed around client applications. MSAL.NET 提供两个独立的类:PublicClientApplicationConfidentialClientApplicationIt provides two separate classes: PublicClientApplication and ConfidentialClientApplication

  • 获取令牌:ADAL.NET 和 MSAL.NET 具有相同的身份验证调用(适用于 ADAL.NET 的 AcquireTokenAsyncAcquireTokenSilentAsync,以及 MSAL.NET 中的 AcquireTokenInteractiveAcquireTokenSilent),但需要不同的参数。Acquiring Tokens: ADAL.NET and MSAL.NET have the same authentication calls (AcquireTokenAsync and AcquireTokenSilentAsync for ADAL.NET, and AcquireTokenInteractive and AcquireTokenSilent in MSAL.NET) but with different parameters required. 不同之处在于,在 MSAL.NET 中,不再需要在每个 AcquireTokenXX 调用中传入应用程序的 ClientIDOne difference is the fact that, in MSAL.NET, you no longer have to pass in the ClientID of your application in every AcquireTokenXX call. 实际上,只需在生成 IPublicClientApplicationIConfidentialClientApplication 时设置 ClientID 一次。Indeed, the ClientID is set only once when building the (IPublicClientApplication or IConfidentialClientApplication).

IAccount 不是 IUserIAccount not IUser

ADAL.NET 操控用户。ADAL.NET manipulated users. 但是,用户是人类或软件代理,可以拥有/负责 Microsoft 标识系统中的一个或多个帐户(若干 Azure AD 帐户、Azure AD B2C)。However, a user is a human or a software agent, but it can possess/own/be responsible for one or more accounts in the Microsoft identity system (several Azure AD accounts, Azure AD B2C).

MSAL.NET 2.x 现在定义了帐户的概念(通过 IAccount 接口)。MSAL.NET 2.x now defines the concept of Account (through the IAccount interface). 这项中断性变更提供了正确的语义:同一用户可以在不同的 Azure AD 目录中拥有多个帐户这一事实。This breaking change provides the right semantics: the fact that the same user can have several accounts, in different Azure AD directories. 此外,由于系统会提供主帐户信息,MSAL.NET 可以在来宾方案中提供更有用的信息。Also MSAL.NET provides better information in guest scenarios, as home account information is provided.

有关 IUser 与 IAccount 之间的差异的详细信息,请参阅 MSAL.NET 2.xFor more information about the differences between IUser and IAccount, see MSAL.NET 2.x.

异常Exceptions

“需要交互”异常Interaction required exceptions

MSAL.NET 提供更明确的异常。MSAL.NET has more explicit exceptions. 例如,当 ADAL 中的无提示身份验证失败时,处理过程是捕获异常并查找 user_interaction_required 错误代码:For example, when silent authentication fails in ADAL the procedure is to catch the exception and look for the user_interaction_required error code:

catch(AdalException exception)
{
 if (exception.ErrorCode == "user_interaction_required")
 {
  try
  {“try to authenticate interactively”}}
 }
}

请参阅使用 ADAL.NET 获取令牌的建议模式中的详细信息See details in The recommended pattern to acquire a token with ADAL.NET

使用 MSAL.NET 可以根据 AcquireTokenSilent 中所述捕获 MsalUiRequiredExceptionUsing MSAL.NET, you catch MsalUiRequiredException as described in AcquireTokenSilent.

catch(MsalUiRequiredException exception)
{
 try {“try to authenticate interactively”}
}

处理声明质询异常Handling claim challenge exceptions

在 ADAL.NET 中,声明质询异常按以下方式进行处理:In ADAL.NET, claim challenge exceptions are handled in the following way:

  • AdalClaimChallengeException 是当资源需要用户的更多声明时(例如,使用双重身份验证时),服务引发的异常(派生自 AdalServiceException)。AdalClaimChallengeException is an exception (deriving from AdalServiceException) thrown by the service in case a resource requires more claims from the user (for instance two-factors authentication). Claims 成员包含某个带有预期声明的 JSON 片段。The Claims member contains some JSON fragment with the claims, which are expected.
  • 在 ADAL.NET 中,接收此异常的公共客户端应用程序需要调用包含声明参数的 AcquireTokenInteractive 重写。Still in ADAL.NET, the public client application receiving this exception needs to call the AcquireTokenInteractive override having a claims parameter. AcquireTokenInteractive 重写甚至不会尝试命中缓存,因为缓存是不必要的。This override of AcquireTokenInteractive does not even try to hit the cache as it is not necessary. 原因在于,缓存中的令牌没有适当的声明(否则不会引发 AdalClaimChallengeException)。The reason is that the token in the cache does not have the right claims (otherwise an AdalClaimChallengeException would not have been thrown). 因此,没有必要查找缓存。Therefore, there is no need to look at the cache. 请注意,可以在执行 OBO 的 Web API 中接收 ClaimChallengeException,而 AcquireTokenInteractive 需要在调用此 Web API 的公共客户端应用程序中调用。Note that the ClaimChallengeException can be received in a WebAPI doing OBO, whereas the AcquireTokenInteractive needs to be called in a public client application calling this web API.
  • 有关详细信息(包括示例),请参阅处理 AdalClaimChallengeExceptionfor details, including samples see Handling AdalClaimChallengeException

在 MSAL.NET 中,声明质询异常按以下方式进行处理:In MSAL.NET, claim challenge exceptions are handled in the following way:

  • ClaimsMsalServiceException 中显示。The Claims are surfaced in the MsalServiceException.
  • 可对 AcquireTokenInteractive 生成器应用一个 .WithClaim(claims) 方法。There is a .WithClaim(claims) method that can apply to the AcquireTokenInteractive builder.

支持的授权Supported grants

有些授权在 MSAL.NET 和 v2.0 终结点中尚不受支持。Not all the grants are yet supported in MSAL.NET and the v2.0 endpoint. 下面汇总了 ADAL.NET 和 MSAL.NET 支持的授权的对比。The following is a summary comparing ADAL.NET and MSAL.NET's supported grants.

公共客户端应用程序Public client applications

下面是适用于桌面和移动应用程序的 ADAL.NET 与 MSAL.NET 支持的授权Here are the grants supported in ADAL.NET and MSAL.NET for Desktop and Mobile applications

授予Grant ADAL.NETADAL.NET MSAL.NETMSAL.NET
交互Interactive 交互式身份验证Interactive Auth 在 MSAL.NET 中以交互方式获取令牌Acquiring tokens interactively in MSAL.NET
Windows 集成身份验证Integrated Windows Authentication Windows 上的集成身份验证 (Kerberos)Integrated authentication on Windows (Kerberos) Windows 集成身份验证Integrated Windows Authentication
用户名/密码Username / Password 使用用户名和密码获取令牌Acquiring tokens with username and password 用户名/密码身份验证Username Password Authentication
设备代码流Device code flow 没有 Web 浏览器的设备的设备配置文件Device profile for devices without web browsers 设备代码流Device Code flow

机密客户端应用程序Confidential client applications

下面是适用于 Web 应用程序、Web API 和守护程序应用程序的 ADAL.NET 与 MSAL.NET 支持的授权:Here are the grants supported in ADAL.NET and MSAL.NET for web applications, web APIs, and daemon applications:

应用类型Type of App 授予Grant ADAL.NETADAL.NET MSAL.NETMSAL.NET
Web 应用、Web API、守护程序Web app, web API, daemon 客户端凭据Client Credentials ADAL.NET 中的客户端凭据流Client credential flows in ADAL.NET MSAL.NET 中的客户端凭据流Client credential flows in MSAL.NET
Web APIWeb API 代表On behalf of 代表用户使用 ADAL.NET 进行服务到服务的调用Service to service calls on behalf of the user with ADAL.NET 在 MSAL.NET 中代表On behalf of in MSAL.NET
Web 应用Web app 身份验证代码Auth Code 使用 ADAL.NET 通过 Web 应用中的授权代码获取令牌Acquiring tokens with authorization codes on web apps with ADAL.NET 使用 MSAL.NET 通过 Web 应用中的授权代码获取令牌Acquiring tokens with authorization codes on web apps with A MSAL.NET

缓存持久性Cache persistence

ADAL.NET 允许使用 BeforeAccessBeforeWrite 方法扩展 TokenCache 类,以便在没有安全存储的平台(.NET Framework 和.NET Core)上实现所需的持久性功能。ADAL.NET allows you to extend the TokenCache class to implement the desired persistence functionality on platforms without a secure storage (.NET Framework and .NET core) by using the BeforeAccess, and BeforeWrite methods. 有关详细信息,请参阅 ADAL.NET 中的令牌缓存序列化For details, see Token Cache Serialization in ADAL.NET.

MSAL.NET 将令牌缓存用作密封类,并消除了扩展该类的功能。MSAL.NET makes the token cache a sealed class, removing the ability to extend it. 因此,令牌缓存持久性的实现必须采用与密封令牌缓存交互的帮助器类的形式。Therefore, your implementation of token cache persistence must be in the form of a helper class that interacts with the sealed token cache. MSAL.NET 中的令牌缓存序列化中介绍了这种交互。This interaction is described in Token Cache Serialization in MSAL.NET.

通用颁发机构的作用Signification of the common authority

在 v1.0 中,如果你使用 https://login.partner.microsoftonline.cn/common 颁发机构,则会允许用户使用任何 AAD 帐户(适用于任何组织)登录。In v1.0, if you use the https://login.partner.microsoftonline.cn/common authority, you will allow users to sign in with any AAD account (for any organization). 请参阅 ADAL.NET 中的颁发机构验证See Authority Validation in ADAL.NET

如果你使用 v2.0 中的 https://login.partner.microsoftonline.cn/common 颁发机构,则会允许用户使用任何 AAD 组织登录。If you use the https://login.partner.microsoftonline.cn/common authority in v2.0, you will allow users to sign in with any AAD organization. 在 MSAL.NET 中,如果你想要限制为使用任何 AAD 帐户登录(与在 ADAL.NET 中的行为相同),则需要使用 https://login.partner.microsoftonline.cn/organizationsIn MSAL.NET, if you want to restrict login to any AAD account (same behavior as with ADAL.NET), you need to use https://login.partner.microsoftonline.cn/organizations. 有关详细信息,请参阅公共客户端应用程序中的 authority 参数。For details, see the authority parameter in public client application.

v1.0 和 v2.0 令牌v1.0 and v2.0 tokens

有两种令牌版本:There are two versions of tokens:

  • v1.0 令牌v1.0 tokens
  • v2.0 令牌v2.0 tokens

v1.0 终结点(由 ADAL 使用)只发出 v1.0 令牌。The v1.0 endpoint (used by ADAL) only emits v1.0 tokens.

但是,v2.0 终结点(由 MSAL 使用)可发出 Web API 所接受的令牌版本。However, the v2.0 endpoint (used by MSAL) emits the version of the token that the web API accepts. 开发人员可以使用 Web API 应用程序清单的属性来选择接受的令牌版本。A property of the application manifest of the web API enables developers to choose which version of token is accepted. 请参阅应用程序清单参考文档中的 accessTokenAcceptedVersionSee accessTokenAcceptedVersion in the Application manifest reference documentation.

有关 v1.0 和 v2.0 令牌的详细信息,请参阅 Azure Active Directory 访问令牌For more information about v1.0 and v2.0 tokens, see Azure Active Directory access tokens

接受 v1.0 令牌的 Web API 的范围Scopes for a web API accepting v1.0 tokens

OAuth2 权限是 v1.0 Web API(资源)应用程序向客户端应用程序公开的权限范围。OAuth2 permissions are permission scopes that a v1.0 web API (resource) application exposes to client applications. 在许可期间,可将这些权限范围授予客户端应用程序。These permission scopes may be granted to client applications during consent. 请参阅 Azure Active Directory 应用程序清单中有关 oauth2Permissions 的部分。See the section about oauth2Permissions in Azure Active Directory application manifest.

将请求访问权限范围限定为 v1.0 应用程序的特定 OAuth2 权限Scopes to request access to specific OAuth2 permissions of a v1.0 application

若要获取接受 v1.0 令牌的应用程序(例如 Microsoft Graph API,网址为 https://microsoftgraph.chinacloudapi.cn) )的令牌,则需要将所需的资源标识符与该资源所需的 OAuth2 权限进行连接以创建 scopesIf you want to acquire tokens for an application accepting v1.0 tokens (for instance the Microsoft Graph API, which is https://microsoftgraph.chinacloudapi.cn), you'd need to create scopes by concatenating a desired resource identifier with a desired OAuth2 permission for that resource.

例如,若要以用户名访问应用 ID URI 为 ResourceId 的 v1.0 Web API,需要使用:For instance, to access in the name of the user a v1.0 web API which App ID URI is ResourceId, you'd want to use:

var scopes = new [] {  ResourceId+"/user_impersonation"};

若要使用 Microsoft Graph API (https://microsoftgraph.chinacloudapi.cn/) 通过 MSAL.NET Azure Active Directory 进行读取和写入,需要按以下代码片段所示创建范围列表:If you want to read and write with MSAL.NET Azure Active Directory using the Microsoft Graph API (https://microsoftgraph.chinacloudapi.cn/), you would create a list of scopes like in the following snippet:

ResourceId = "https://microsoftgraph.chinacloudapi.cn/";
var scopes = new [] { ResourceId + "Directory.Read", ResourceID + "Directory.Write"}

警告:应在对应于 v1.0 Web API 的范围中使用一个或两个斜杠Warning: Should you have one or two slashes in the scope corresponding to a v1.0 web API

若要写入对应于 Azure 资源管理器 API (https://management.core.chinacloudapi.cn/) 的范围,需要请求以下范围(请注意有两个斜杠)If you want to write the scope corresponding to the Azure Resource Manager API (https://management.core.chinacloudapi.cn/), you need to request the following scope (note the two slashes)

var scopes = new[] {"https://management.core.chinacloudapi.cn//user_impersonation"};
var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

// then call the API: https://management.chinacloudapi.cn/subscriptions?api-version=2016-09-01

这是因为,资源管理器 API 要求在其受众声明 (aud) 中使用一个斜杠,然后使用一个斜杠来分隔 API 名称与范围。This is because the Resource Manager API expects a slash in its audience claim (aud), and then there is a slash to separate the API name from the scope.

下面是 Azure AD 使用的逻辑:The logic used by Azure AD is the following:

  • 对于使用 v1.0 访问令牌(只能使用此类令牌)的 ADAL (v1.0) 终结点,aud=resourceFor ADAL (v1.0) endpoint with a v1.0 access token (the only possible), aud=resource
  • 对于要求资源访问令牌接受 v2.0 令牌的 MSAL(v2.0 终结点),aud=resource.AppIdFor MSAL (v2.0 endpoint) asking an access token for a resource accepting v2.0 tokens, aud=resource.AppId
  • 对于要求资源访问令牌接受 v1.0 令牌的 MSAL(v2.0 终结点)(与上面的情况相同),Azure AD 将提取最后一个斜杠前面的所有内容并将其用作资源标识符,以分析请求的范围中的所需受众。For MSAL (v2.0 endpoint) asking an access token for a resource accepting a v1.0 access token (which is the case above), Azure AD parses the desired audience from the requested scope by taking everything before the last slash and using it as the resource identifier. 因此,如果 https://database.chinacloudapi.cn 预期的受众为“https://database.chinacloudapi.cn/ ”,则需要请求的范围为 https:/ /database.chinacloudapi.cn//.default。Therefore if https://database.chinacloudapi.cn expects an audience of "https://database.chinacloudapi.cn/", you'll need to request a scope of https://database.chinacloudapi.cn//.default. 另请参阅问题 #747:将省略资源 URL 的尾部斜杠,因为该斜杠会导致 SQL 身份验证失败 #747See also issue #747: Resource url's trailing slash is omitted, which caused sql auth failure #747

将请求访问权限范围限定为 v1.0 应用程序的所有权限Scopes to request access to all the permissions of a v1.0 application

例如,若要获取 v1.0 应用程序的所有静态范围的令牌,则需要使用For instance, if you want to acquire a token for all the static scopes of a v1.0 application, one would need to use

ResourceId = "someAppIDURI";
var scopes = new [] {  ResourceId+"/.default"};

在客户端凭据流/守护程序应用中限定请求范围Scopes to request in the case of client credential flow / daemon app

使用客户端凭据流时,要传递的范围也是 /.defaultIn the case of client credential flow, the scope to pass would also be /.default. 此范围会让 Azure AD 知道管理员在应用程序注册中许可的所有应用级权限。This scope tells to Azure AD: "all the app-level permissions that the admin has consented to in the application registration.

ADAL 到 MSAL 的迁移ADAL to MSAL migration

ADAL.NET v2.X 中公开了刷新令牌,使你能够通过缓存这些令牌并使用 ADAL 2.x 提供的 AcquireTokenByRefreshToken 方法,来围绕这些令牌的使用开发解决方案。In ADAL.NET v2.X, the refresh tokens were exposed allowing you to develop solutions around the use of these tokens by caching them and using the AcquireTokenByRefreshToken methods provided by ADAL 2.x. 其中的某些解决方案在如下所述的场景中使用:Some of those solutions were used in scenarios such as:

  • 当用户不再保持连接时,长时间运行的服务代表用户执行仪表板刷新等操作。Long running services that do actions including refreshing dashboards on behalf of the users whereas the users are no longer connected.
  • 在 Web 场场景中,让客户端将 RT 引入 Web 服务(缓存在客户端以加密 Cookie 的形式执行,而不是在服务器端执行)WebFarm scenarios for enabling the client to bring the RT to the web service (caching is done client side, encrypted cookie, and not server side)

出于安全原因,MSAL.NET 不公开刷新令牌:MSAL 会为你处理刷新令牌。MSAL.NET does not expose refresh tokens, for security reasons: MSAL handles refreshing tokens for you.

幸运的是,MSAL.NET 现在会提供一个 API 用于将以前的刷新令牌(通过 ADAL 获取)迁移到 IConfidentialClientApplication 中:Fortunately, MSAL.NET now has an API that allows you to migrate your previous refresh tokens (acquired with ADAL) into the IConfidentialClientApplication:

/// <summary>
/// Acquires an access token from an existing refresh token and stores it and the refresh token into
/// the application user token cache, where it will be available for further AcquireTokenSilent calls.
/// This method can be used in migration to MSAL from ADAL v2 and in various integration
/// scenarios where you have a RefreshToken available.
/// (see https://aka.ms/msal-net-migration-adal2-msal2)
/// </summary>
/// <param name="scopes">Scope to request from the token endpoint.
/// Setting this to null or empty will request an access token, refresh token and ID token with default scopes</param>
/// <param name="refreshToken">The refresh token from ADAL 2.x</param>
IByRefreshToken.AcquireTokenByRefreshToken(IEnumerable<string> scopes, string refreshToken);

使用此方法可以结合所需的任何范围(资源)提供以前用过的刷新令牌。With this method, you can provide the previously used refresh token along with any scopes (resources) you desire. 该刷新令牌将交换一个新令牌,并缓存到应用程序中。The refresh token will be exchanged for a new one and cached into your application.

由于此方法适用于非典型的场景,因此,在未事先将 IConfidentialClientApplication 强制转换为 IByRefreshToken 的情况下,不能现成地使用它来访问刷新令牌。As this method is intended for scenarios that are not typical, it is not readily accessible with the IConfidentialClientApplication without first casting it to IByRefreshToken.

以下代码片段演示了机密客户端应用程序中的一些迁移代码。This code snippet shows some migration code in a confidential client application. GetCachedRefreshTokenForSignedInUser 检索利用 ADAL 2.x 的某个旧版应用程序存储在某个存储中的刷新令牌。GetCachedRefreshTokenForSignedInUser retrieve the refresh token that was stored in some storage by a previous version of the application that used to leverage ADAL 2.x. GetTokenCacheForSignedInUser 反序列化已登录用户的缓存(因为机密客户端应用程序应该为每个用户配置一个缓存)。GetTokenCacheForSignedInUser deserializes a cache for the signed-in user (as confidential client applications should have one cache per user).

TokenCache userCache = GetTokenCacheForSignedInUser();
string rt = GetCachedRefreshTokenForSignedInUser();

IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(clientId)
 .WithAuthority(Authority)
 .WithRedirectUri(RedirectUri)
 .WithClientSecret(ClientSecret)
 .Build();
IByRefreshToken appRt = app as IByRefreshToken;

AuthenticationResult result = await appRt.AcquireTokenByRefreshToken(null, rt)
                                         .ExecuteAsync()
                                         .ConfigureAwait(false);

将会看到,AuthenticationResult 中返回了一个访问令牌和 ID 令牌,而新的刷新令牌已存储在缓存中。You will see an access token and ID token returned in your AuthenticationResult while your new refresh token is stored in the cache.

对于可提供刷新令牌的各种集成方案,也可以使用此方法。You can also use this method for various integration scenarios where you have a refresh token available.

后续步骤Next steps

可以 Microsoft 标识平台终结点中的范围、权限和许可中找到有关范围的详细信息You can find more information about the scopes in Scopes, permissions, and consent in the Microsoft identity platform endpoint