如何在 MSAL .Net C# 中获取刷新令牌

How to get refresh token in MSAL .Net C#

我确定了两种在 EWS 的 MSAL 中获取令牌的方法

  1. 使用用户名密码方法。
  2. 使用 Daemon Confidential 方法。

在获取token后,以上两种方法都无法刷新。虽然我试图遵循 MS 文档但没有成功。 GetAccountsAsync() 总是给出空结果。

这是我的用户名密码方法代码

var publicClientApplication = PublicClientApplicationBuilder.Create(ClientId)
                 .WithAuthority(AzureCloudInstance.AzurePublic, TenantId).Build();
var accounts = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult();
var result = publicClientApplication
                 .AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                 .ExecuteAsync().GetAwaiter().GetResult();

任何人都可以指导我为什么会这样,或者是否有解释此流程的文档。

MSAL maintains a token cache and caches a token after it has been acquired. It's also capable of refreshing a token when it's getting close to expiration (as the token cache also contains a refresh token).

出于安全原因,

MSAL.NET 不会公开刷新令牌:MSAL 使用令牌缓存为您处理刷新令牌。

当你 GetAccountsAsync() 总是空着的时候,你的 Token Cache serialization.

默认情况下,访问令牌在 1 小时后过期,如果 AAD 在令牌过期时正忙,您的应用程序将变得不可用,因为您无法获取有效的访问令牌。您可以通过定期 forcing a refresh 来提高应用程序的可用性。我们建议每 30 分钟强制刷新一次,或者如果这是自定义生命周期,则强制刷新 AT 生命周期的一半。

result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
             .WithForceRefresh(true)
             .ExecuteAsync();