public void MigrateFromAdalToMsal() { MsalCacheHelper cacheHelper = null; var builder = PublicClientApplicationBuilder.Create(PowerShellClientId); var clientApplication = builder.Build(); clientApplication.UserTokenCache.SetBeforeAccess((TokenCacheNotificationArgs args) => { if (AdalToken != null) { try { args.TokenCache.DeserializeAdalV3(AdalToken); } catch (Exception) { //TODO: } finally { AdalToken = null; if (!HasRegistered) { HasRegistered = true; cacheHelper = MsalCacheHelperProvider.GetCacheHelper(); cacheHelper.RegisterCache(clientApplication.UserTokenCache); } } } }); clientApplication.UserTokenCache.SetAfterAccess((TokenCacheNotificationArgs args) => { if (args.HasStateChanged) { var bytes = args.TokenCache.SerializeAdalV3(); } }); var accounts = clientApplication.GetAccountsAsync().ConfigureAwait(false).GetAwaiter().GetResult(); foreach (var account in accounts) { try { var accountEnvironment = string.Format("https://{0}/", account.Environment); var environment = AzureEnvironment.PublicEnvironments.Values.Where(e => e.ActiveDirectoryAuthority == accountEnvironment).FirstOrDefault(); if (environment == null) { // We cannot map the previous environment to one of the public environments continue; } var scopes = new string[] { string.Format("{0}{1}", environment.ActiveDirectoryServiceEndpointResourceId, ".default") }; try { clientApplication.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } catch //For MSA account, real AAD tenant must be specified, otherwise MSAL library will request token against its home tenant { var tenantId = GetTenantId(account.Username); if (!string.IsNullOrEmpty(tenantId)) { clientApplication.AcquireTokenSilent(scopes, account).WithAuthority(environment.ActiveDirectoryAuthority, tenantId).ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } } //TODO: Set HomeAccountId for migration } catch { // Continue if we're unable to get the token for the current account continue; } } cacheHelper?.UnregisterCache(clientApplication.UserTokenCache); }
/// <summary> /// Unregisters a token cache so it no longer synchronizes with on disk storage. /// </summary> /// <param name="tokenCache"></param> public virtual void UnregisterCache(ITokenCache tokenCache) { _helper.UnregisterCache(tokenCache); }