如何在应用程序中使用启用了连续访问评估的 APIHow to use Continuous Access Evaluation enabled APIs in your applications

连续访问评估 (CAE) 是一种新兴的行业标准,它允许根据关键事件策略评估撤销访问令牌,而不是依赖基于生存期的令牌过期。Continuous Access Evaluation (CAE) is an emerging industry standard that allows access tokens to be revoked based on critical events and policy evaluation rather than relying on token expiry based on lifetime. 对于某些资源 API,由于风险和策略是实时评估的,因此这可能会将令牌生存期提高到最多 28 小时。For some resource APIs, because risk and policy are evaluated in real time, this can increase token lifetime up to 28 hours. Microsoft 身份验证库 (MSAL) 将主动刷新这些生存期较长的令牌,从而提高应用程序的复原能力。These long-lived tokens will be proactively refreshed by the Microsoft Authentication Library (MSAL), increasing the resiliency of your applications.

本文介绍如何在应用程序中使用启用了 CAE 的 API。This article shows you how to use CAE-enabled APIs in your applications.

实现注意事项Implementation considerations

若要使用连续访问评估,应用及其访问的资源 API 必须已启用 CAE。To use Continuous Access Evaluation, both your app and the resource API it's accessing must be CAE-enabled. 但是,准备代码以使用启用了 CAE 的资源不会阻止你使用未启用 CAE 的 API。However, preparing your code to use a CAE enabled resource will not prevent you from using APIs that are not CAE enabled.

如果资源 API 实现了 CAE,并且你的应用程序声明它可以处理 CAE,那么你的应用将会获取该资源的 CAE 标记。If a resource API implements CAE and your application declares it can handle CAE, your app will get CAE tokens for that resource. 出于此原因,如果声明了应用已 CAE 就绪,那么你的应用程序必须为所有接受 Microsoft 标识访问令牌的资源 API 处理 CAE 声明质询。For this reason, if you declare your app CAE ready, your application must handle the CAE claim challenge for all resource APIs that accept Microsoft Identity access tokens. 如果未在这些 API 调用中处理 CAE 响应,你的应用程序可能会在使用一个仍处于已返回的令牌生存期内,但由于 CAE 而被撤销的令牌来重试 API 调用的循环中结束。If you do not handle CAE responses in these API calls, your app could end up in a loop retrying an API call with a token that is still in the returned lifespan of the token but has been revoked due to CAE.

代码The code

第一步是添加代码以处理由于 CAE 而拒绝该调用的资源 API 的响应。The first step is to add code to handle a response from the resource API rejecting the call due to CAE. 启用 CAE 后,当访问令牌已被撤销或者 API 检测到所使用的 IP 地址发生变化时,API 将返回 401 状态和 WWW-Authenticate 标头。With CAE, APIs will return a 401 status and a WWW-Authenticate header when the access token has been revoked or the API detects a change in IP address used. WWW-Authenticate 标头包含一个声明质询,应用程序可以使用该质询来获取新的访问令牌。The WWW-Authenticate header contains a Claims Challenge that the application can use to acquire a new access token.

例如:For example:

HTTP 401; Unauthorized
WWW-Authenticate=Bearer
 authorization_uri="https://login.chinacloudapi.cn/common/oauth2/authorize",
 error="insufficient_claims",
 claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwNDEwNjY1MSJ9fX0="

你的应用将检查以下内容:Your app would check for:

  • 返回 401 状态的 API 调用the API call returning the 401 status
  • 是否存在包含以下参数的 WWW-Authenticate 标头:the existence of a WWW-Authenticate header containing:
    • 值为“insufficient_claims”的“error”参数an "error" parameter with the value "insufficient_claims"
    • “claims”参数a "claims" parameter

满足这些条件时,应用可以提取声明质询并对其进行解码。When these conditions are met, the app can extract and decode the claims challenge.

if (APIresponse.IsSuccessStatusCode)
{
    // . . .
}
else
{
    if (APIresponse.StatusCode == System.Net.HttpStatusCode.Unauthorized
        && APIresponse.Headers.WwwAuthenticate.Any())
    {
        AuthenticationHeaderValue bearer = APIresponse.Headers.WwwAuthenticate.First
            (v => v.Scheme == "Bearer");
        IEnumerable<string> parameters = bearer.Parameter.Split(',').Select(v => v.Trim()).ToList();
        var error = GetParameter(parameters, "error");

        if (null != error && "insufficient_claims" == error)
        {
            var claimChallengeParameter = GetParameter(parameters, "claims");
            if (null != claimChallengeParameter)
            {
                var claimChallengebase64Bytes = System.Convert.FromBase64String(claimChallengeParameter);
                var claimChallenge = System.Text.Encoding.UTF8.GetString(claimChallengebase64Bytes);
                var newAccessToken = await GetAccessTokenWithClaimChallenge(scopes, claimChallenge);

然后,你的应用将使用声明质询获取资源的新访问令牌。Your app would then use the claims challenge to acquire a new access token for the resource.

try
{
    authResult = await _clientApp.AcquireTokenSilent(scopes, firstAccount)
        .WithClaims(claimChallenge)
        .ExecuteAsync()
        .ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
    try
    {
        authResult = await _clientApp.AcquireTokenInteractive(scopes)
            .WithClaims(claimChallenge)
            .WithAccount(firstAccount)
            .ExecuteAsync()
            .ConfigureAwait(false);
    }
    // . . .

一旦你的应用程序准备好处理启用了 CAE 的资源返回的声明质询,你就可以告诉 Microsoft 标识你的应用已 CAE 就绪。Once your application is ready to handle the claim challenge returned by a CAE enabled resource, you can tell Microsoft Identity your app is CAE ready. 若要在 MSAL 应用程序中执行此操作,请使用“cp1”的客户端功能构建公共客户端。To do this in your MSAL application, build your Public Client using the Client Capabilities of "cp1".

_clientApp = PublicClientApplicationBuilder.Create(App.ClientId)
    .WithDefaultRedirectUri()
    .WithAuthority(authority)
    .WithClientCapabilities(new [] {"cp1"})
    .Build();

可以通过使用户登录到应用程序,然后使用 Azure 门户撤销用户会话,来测试应用程序。You can test your application by signing in a user to the application then using the Azure portal to Revoke the user's sessions. 应用下次调用启用了 CAE 的 API 时,系统将要求用户重新进行身份验证。The next time the app calls the CAE enabled API, the user will be asked to reauthenticate.

后续步骤Next steps

若要了解详细信息,请参阅连续访问评估To learn more, see Continuous access evaluation.