【发布时间】:2019-12-07 02:09:57
【问题描述】:
我需要有关如何检索存储的 MSAL 令牌的帮助,以便在我的应用程序的执行中重复使用它。
场景:
我正在关注this Microsoft demo,它展示了如何使用 MSAL 获取 Oauth2 令牌,以便在控制台应用程序中对 EWS 进行身份验证。它工作正常,每次运行应用程序时都会弹出一个交互式登录窗口以获取令牌。
我现在想在以后独立执行应用程序时使用相同的令牌(或其刷新令牌,如果原始令牌已过期)。
最终,我想实现一个应用程序,用户通过我的 Web UI 提供初始交互式 Oauth 登录,从那时起,我存储与 EWS 邮箱交互的后台应用程序的令牌,并在需要时执行刷新.
我正在尝试什么:
我一直在尝试理解基于本地文件的令牌缓存的“naive implementation”。我可以看到它正在创建一个本地文件,但是我怎样才能让它在以后的执行中检查这个文件,并使用它存储在那里的令牌。然后我找到了通往this MSAL extension library 的方法,但它没有文档,我什至无法适应它的测试。
我的代码:
static async System.Threading.Tasks.Task MainAsync(string[] args)
{
// Configure the MSAL client to get tokens
var pcaOptions = new PublicClientApplicationOptions
{
ClientId = ConfigurationManager.AppSettings["appId"],
TenantId = ConfigurationManager.AppSettings["tenantId"]
};
var pca = PublicClientApplicationBuilder
.CreateWithApplicationOptions(pcaOptions).Build();
TokenCacheHelper.EnableSerialization(pca.UserTokenCache); // added based on 'naive implementation'
var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };
try
{
// Make the interactive token request
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync(); // must have to change this to something else that is aware of the cache?
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
// Make an EWS call
// ... do stuff in EWS ...
}
}
帮助代码(来自'naive implementation')
static class TokenCacheHelper
{
public static void EnableSerialization(ITokenCache tokenCache)
{
tokenCache.SetBeforeAccess(BeforeAccessNotification);
tokenCache.SetAfterAccess(AfterAccessNotification);
}
/// <summary>
/// Path to the token cache
/// </summary>
public static readonly string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin3";
private static readonly object FileLock = new object();
private static void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
lock (FileLock)
{
args.TokenCache.DeserializeMsalV3(File.Exists(CacheFilePath)
? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
null,
DataProtectionScope.CurrentUser)
: null);
}
}
private static void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
if (args.HasStateChanged)
{
lock (FileLock)
{
// reflect changesgs in the persistent store
File.WriteAllBytes(CacheFilePath,
ProtectedData.Protect(args.TokenCache.SerializeMsalV3(),
null,
DataProtectionScope.CurrentUser)
);
}
}
}
}
【问题讨论】:
标签: .net oauth-2.0 azure-active-directory exchangewebservices msal