gpt4 book ai didi

c# - 使用 C# 登录 Azure AD。获取刷新 token 和访问 token

转载 作者:行者123 更新时间:2023-12-05 05:01:48 27 4
gpt4 key购买 nike

任务:我需要创建一个 WPF 应用程序,它将与 EWS(Exchange 网络服务)一起工作。我也有 2 个限制:

  • 登录应该只进行一次(它应该使用刷新 token 重新连接)
  • 它应该支持 2FA

我的解决方案部分:我使用 OAuth 连接到 Azure AD。作为 OAuth 客户端,我使用 Microsoft.Identity.Client。对于第一次登录,我有这样的代码:

var pcaOptions = new PublicClientApplicationOptions
{
ClientId = *my_client_id*,
TenantId = *my_tenant*
};
AuthenticationResult authResult = pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync().Result;

这部分代码显示一个 WPF 窗口,我在其中输入凭据并返回一个结果 (AuthenticationResult),其中包含访问 token 。

问题: AuthenticationResult 没有刷新 token ,所以我无法满足第一个限制。有什么解决办法或者方法吗?

附加问题:如何使用 Microsoft.Identity.Client 更新刷新 token ?

最佳答案

出于安全原因,MSAL.NET 不公开刷新 token :MSAL 使用 token 缓存为您处理刷新 token 。

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).

您可以通过定期使用 WithForceRefresh 来提高应用程序的可用性当设置为 true

时,它将在内部获取新的访问 token
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.WithForceRefresh(true)
.ExecuteAsync();

关于c# - 使用 C# 登录 Azure AD。获取刷新 token 和访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62560052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com