使用 MSAL.NET 从令牌缓存获取令牌Get a token from the token cache using MSAL.NET

使用适用于 .NET 的 Microsoft 身份验证库 (MSAL.NET) 获取访问令牌时,将缓存该令牌。When you acquire an access token using Microsoft Authentication Library for .NET (MSAL.NET), the token is cached. 应用程序需要令牌时,应该首先调用 AcquireTokenSilent 方法来验证缓存中是否有可接受的令牌。When the application needs a token, it should first call the AcquireTokenSilent method to verify if an acceptable token is in the cache. 在许多情况下,可以基于缓存中的令牌获取具有更多范围的另一个令牌。In many cases, it's possible to acquire another token with more scopes based on a token in the cache. 当令牌快到期时也可以刷新令牌(因为令牌缓存也包含一个刷新令牌)。It's also possible to refresh a token when it's getting close to expiration (as the token cache also contains a refresh token).

建议的模式是首先调用 AcquireTokenSilent 方法。The recommended pattern is to call the AcquireTokenSilent method first. 如果 AcquireTokenSilent 失败,则使用其他方法获取令牌。If AcquireTokenSilent fails, then acquire a token using other methods.

在以下示例中,应用程序首先尝试从令牌缓存中获取令牌。In the following example, the application first attempts to acquire a token from the token cache. 如果引发了 MsalUiRequiredException 异常,则应用程序将以交互方式获取令牌。If a MsalUiRequiredException exception is thrown, the application acquires a token interactively.

AuthenticationResult result = null;
var accounts = await app.GetAccountsAsync();

try
{
 result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
        .ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
 // A MsalUiRequiredException happened on AcquireTokenSilent.
 // This indicates you need to call AcquireTokenInteractive to acquire a token
 System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

 try
 {
    result = await app.AcquireTokenInteractive(scopes)
          .ExecuteAsync();
 }
 catch (MsalException msalex)
 {
    ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
 }
}
catch (Exception ex)
{
 ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
 return;
}

if (result != null)
{
 string accessToken = result.AccessToken;
 // Use the token
}